post 请求方式-form-data

private final static int CONNECT_TIME_OUT = 18000;
private final static int READ_OUT_TIME = 18000;

/**
 * java post 请求 form-data 表单形式提交
 */
public static JSONObject post(List pairs, String urlPath) {
    HttpClient httpClient = null;
    HttpPost methodPost = null;
    if (null == httpClient) {
        httpClient = HttpClientBuilder.create().build();
    }
    if (null == methodPost) {
        methodPost = new HttpPost(urlPath);
    }
    String returnStr;
    try {
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIME_OUT).setSocketTimeout(READ_OUT_TIME).build();
        methodPost.setConfig(requestConfig);
        methodPost.setHeader(HTTP.CONTENT_TYPE,"application/x-www-form-urlencoded");
        methodPost.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8"));

        HttpResponse response = httpClient.execute(methodPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {

        } else {
            returnStr = EntityUtils.toString(response.getEntity());
            //字符串转json
            return JSON.parseObject(returnStr);
        }
    } catch (IOException e) {
        e.printStackTrace();
        throw new ServiceException(e.getMessage());
    }
    return null;
}



/**
* post方式 发送 body请求
*
*/
public static String post(JSONObject json, String path) {
	String result = "";
	try {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(path);
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(10000).setSocketTimeout(10000).build();
		post.setConfig(requestConfig);
		//  这几个是设置header头的
		post.setHeader("Content-Type", "appliction/json");
		post.addHeader("X-APP-Id", "pp8t336vCK9");
		post.addHeader("X-APP-Key", "Cn0PboLmab");
		post.addHeader("X-CTG-Request-Id", "123");
		StringEntity s = new StringEntity(json.toString(), "utf-8");
		s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "appliction/json"));
		post.setEntity(s);
		HttpResponse httpResponse = client.execute(post);
		InputStream in = httpResponse.getEntity().getContent();
		BufferedReader br = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
		StringBuilder strber = new StringBuilder();
		String line = null;
		while ((line = br.readLine()) != null) {
			strber.append(line + "\n");

		}
		in.close();
		result = strber.toString();
		if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
			result = "服务器异常";
		}
	} catch (Exception e) {
		System.out.println("请求异常");
		throw new RuntimeException(e);
	}
	//请求返回
	System.out.println("result==" + result);
	return result;
}

你可能感兴趣的:(java,java)