研发效能 null

testly for TesterHome各地沙龙管理群 · 2018年08月26日 · 最后由 zqq 回复于 2018年09月01日 · 2417 次阅读

为 231

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 5 条回复 时间 点赞
阿廉 [该话题已被删除] 中提及了此贴 08月26日 20:38
仅楼主可见
package testCase;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import Trigger.httpclient;
import junit.framework.Assert;
import net.sf.json.JSONObject;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;


public class Test_1 {

    @Test
    public void testMethod() throws Exception {
        List<String> list = Arrays.asList("上海","北京","深圳","广州");
        List<String> wenduList=getYesterdayWendu(list);
        paixu(wenduList);
        System.out.println(wenduList);
    }

    private List<String> getYesterdayWendu(List<String> city)throws Exception{
        String  Url="https://www.sojson.com/open/api/weather/json.shtml";
        List<String> wenduList = new ArrayList<>();
        for(int i=0;i<city.size();i++) {
            String Parameter = "city=" + city.get(i);
            httpclient httpGet = new httpclient();
            JSONObject json = httpGet.sendGet(Url, Parameter);
            String JsonStr = JsonPath.JsonPath(json.toString(), "$..yesterday.high");
            String Wendu = city.get(i) + ":" + JsonStr.substring(JsonStr.indexOf("温") + 2, JsonStr.indexOf("℃"));
            wenduList.add(Wendu);
            System.out.println(Wendu);
            Thread.sleep(4000);
        }
        return wenduList;
    }

    private List paixu(List<String> l){
        int length = l.size();
        for(int i=0; i<length-1; i++){
            for(int j=i+1; j<length; j++) {
                String a = l.get(i);
                String b = l.get(j);
                if (Float.parseFloat(a.split(":")[1]) < Float.parseFloat(b.split(":")[1])) {
                    l.set(i, b);
                    l.set(j, a);
                }
            }
        }
        return l;
    }
}


锋焰 回复

非常棒

Jackyu 回复

package Trigger;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import net.sf.json.JSONObject;
import org.apache.http.HeaderIterator;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.cookie.CookieSpecProvider;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.impl.cookie.BestMatchSpecFactory;
import org.apache.http.impl.cookie.BrowserCompatSpecFactory;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class httpclient {

public static CookieStore cookieStore = new BasicCookieStore();
public CloseableHttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
public static HttpClientContext context = null;

/**
* get 请求
* @param url
* @param Parameter
* @return
* @throws Exception
* @throws ClientProtocolException
*/
public JSONObject sendGet(String url, String Parameter) throws Exception {
StringBuffer responseStr=new StringBuffer();
try {
if(Parameter.isEmpty()==false){url=url + "?" + Parameter;}
HttpGet httpget = new HttpGet(url);
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
System.out.println("----------------------------------------");

InputStream inSm = entity.getContent();
Scanner inScn = new Scanner(inSm,"utf-8");
while (inScn.hasNextLine()) {
responseStr.append(inScn.nextLine().toString());
}

httpget.abort();
} finally {

httpclient.getConnectionManager().shutdown();
}
System.out.println("Response:");
System.out.println("----------------------------------------");
System.out.println(responseStr.toString());
System.out.println("----------------------------------------");
return JSONObject.fromObject(responseStr.toString().trim());
}

/**
* 用 post 请求
* @param url
* @param parameter
* @return
*/

public JSONObject sendPost(String url, String parameter) {
String Response =new String();
HttpPost httpPost = new HttpPost(url);
List formParams = new ArrayList();
FormatProcessing(formParams,parameter);
UrlEncodedFormEntity urlEncodedFormEntity;
try {
urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, "UTF-8");
httpPost.setEntity(urlEncodedFormEntity);
httpPost.setHeader("Content-Type","application/x-www-form-urlencoded");
System.out.println("execurting request:" + httpPost.getURI()+"\nparameter:"+parameter);
HttpResponse httpResponse = null;
httpResponse = httpclient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
String content = EntityUtils.toString(httpEntity, "UTF-8");
Response=content;
}
printResponse(httpResponse);
setContext();
setCookieStore(httpResponse);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭连接,释放资源
httpclient.getConnectionManager().shutdown();
}
System.out.println("Response:");
System.out.println("----------------------------------------");
System.out.println(Response.toString());
System.out.println("----------------------------------------");
return JSONObject.fromObject(Response.toString().trim());
}

/**
* Post 入参转换成 List
* @param formParams
* @param parameter
*/
public static void FormatProcessing (List formParams, String parameter){
try{
String value[] =parameter.split("&");
for(int i=0;i<value.length;i++){
String keyword[]=value[i].split("=");
formParams.add(new BasicNameValuePair(keyword[0], keyword[1]));
}}catch(Exception e){
e.printStackTrace();
System.out.println("入参转换失败");
}

}

/**
* 打印 httpResponse
* @param httpResponse
* @throws ParseException
* @throws IOException
*/
public static void printResponse(HttpResponse httpResponse) throws ParseException, IOException {
HttpEntity entity = httpResponse.getEntity();
System.out.println("status:" + httpResponse.getStatusLine());
HeaderIterator iterator = httpResponse.headerIterator();
while (iterator.hasNext()) {
System.out.println("\t" + iterator.next());
}
if (entity != null) {
try {
String responseString = EntityUtils.toString(entity, "UTF-8");
}catch(Exception E){}

}
}

/**
* 保留 cookie
* @param httpResponse
*/
public static void setCookieStore(HttpResponse httpResponse) {
String setCookie =new String();
if(httpResponse.getFirstHeader("Set-Cookie")!=null) {
setCookie = httpResponse.getFirstHeader("Set-Cookie").getValue();
}
String JSESSIONID =new String();
if(setCookie.isEmpty()==false) {
JSESSIONID = setCookie.substring("JSESSIONID=".length(),
setCookie.indexOf(";"));
}
// 新建一个 Cookie
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID",
JSESSIONID);
cookie.setVersion(0);
cookie.setDomain("127.0.0.1");
cookie.setPath("/CwlProClient");
cookieStore.addCookie(cookie);
}

/**
* 设置 Context
*/
public static void setContext() {
context = HttpClientContext.create();
Registry registry = RegistryBuilder
. create()
.register(CookieSpecs.BEST_MATCH, new BestMatchSpecFactory())
.register(CookieSpecs.BROWSER_COMPATIBILITY,
new BrowserCompatSpecFactory()).build();
context.setCookieSpecRegistry(registry);
context.setCookieStore(cookieStore);
}

/**
* tmain
* @param args
* @throws Exception
/
public static void main(String[] args) throws Exception {
Trigger.httpclient api=new httpclient();
String url ="http://30.17.1.73:8080/APIInterface/GetUserList";
String data="page=1&limit=3";
System.out.println("response:"+api.sendGet(url,data));
/
String url ="http://30.17.1.73:8080/APIInterface/InsertProject";
String data="name=test&remark=test&createuser=test&type=1";
System.out.println(api.sendPost(url,data));*/
}

}

    @Test
    public void testWendu() throws Exception {
        String[] parameters = {"北京", "上海", "深圳", "广州"};
        ArrayList<String> list = new ArrayList();
        for (int i = 0; i < parameters.length; i++) {
            httpclient httpGet = new httpclient();
            JSONObject jsonObject = httpGet.sendGet(Url, "city=" + parameters[i]);
//            String wenduOfYestoday = json.getJSONObject("data").getJSONObject("yesterday").getString("high");
            JsonPath json = new JsonPath();
            String expression = "$..yesterday.high";
            String wenduOfYestoday = json.JsonPath(jsonObject.toString(), expression);
            System.out.println(wenduOfYestoday);

            wenduOfYestoday = wenduOfYestoday.split("( )|(℃)")[1];
            list.add(wenduOfYestoday);
            sleep(5000);
        }

//        Collections.sort(list);
//        System.out.println(list.toString());

        boolean flag = true;
        for (int i = 0; i < list.size(); i++) {
            flag = false;
            for (int j = 0; j < list.size() - 1; j++) {
                float value1 = Float.parseFloat(list.get(j));
                float value2 = Float.parseFloat(list.get(j + 1));
                if (value1 > value2) {
                    list.set(j, String.valueOf(value2));
                    list.set(j + 1, String.valueOf(value1));
                    flag = true;
                }
            }
            if (flag == false) {
                break;
            }
        }
        System.out.println("排序后:" + list.toString());


    }
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册