java发送http请求 utf8,UTF-8中的JAVA Http POST请求

My J2EE application is able to receive POST request from a JSP page, no problem about that.

But if I use another java application to send a POST request, the parameter received is not an UTF-8 string.

Here there is my code:

URL url = new URL("http://localhost:8080/ITUNLPWebInterface/SimpleApi");

HttpURLConnection cox = (HttpURLConnection) url.openConnection();

cox.setDoInput(true);

cox.setDoOutput(true);

cox.setRequestMethod("POST");

cox.setRequestProperty("Accept-Charset", "UTF-8");

cox.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

cox.setRequestProperty("charset", "UTF-8");

DataOutputStream dos = new DataOutputStream(cox.getOutputStream());

String query = "tool=ner&input=şaşaşa";

dos.writeBytes(query);

dos.close();

Am I doing something wrong?

Thanks for your reply

解决方案

this work!!!.

package com.erenerdogan.utils;

import com.erenerdogan.webservice.ServiceInterface;

import java.io.IOException;

import java.io.UnsupportedEncodingException;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;

import org.apache.http.NameValuePair;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.HttpClient;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.impl.client.DefaultHttpClient;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.params.HttpConnectionParams;

import org.apache.http.params.HttpParams;

import org.apache.http.util.EntityUtils;

/**

*

* @author erenerdogan

*/

public class WebService

{

private String server;

public WebService(String server) {

this.server = server;

}

private HttpPost createPostRequest(String method, Map paramPairs){

// Creating HTTP Post

HttpPost httpPost = new HttpPost(server + "/" + method);

// Building post parameters

List nameValuePair = new ArrayList(paramPairs.size());

for (String key : paramPairs.keySet()){

nameValuePair.add(new BasicNameValuePair(key, paramPairs.get(key)));

System.out.println("Key : "+ key + " - Value : "+ paramPairs.get(key) );

}

// Url Encoding the POST parameters

try {

httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair,"UTF-8"));

} catch (UnsupportedEncodingException e) {

// writing error to Log

e.printStackTrace();

}

return httpPost;

}

public String callServer(String method, Map paramPairs) throws ClientProtocolException, IOException{

// Creating HTTP client

HttpClient httpClient = new DefaultHttpClient();

HttpParams httpParameters = httpClient.getParams();

HttpConnectionParams.setConnectionTimeout(httpParameters, 10 * 1000);

HttpConnectionParams.setSoTimeout(httpParameters, 3 * 1000);

HttpResponse httpResponse = httpClient.execute(createPostRequest(method, paramPairs));

HttpEntity httpEntity = httpResponse.getEntity();

String xml = EntityUtils.toString(httpEntity);

return xml;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Java发送带有UTF-8编码的application/json POST请求,可以按照以下步骤进行操作: 1. 导入必要的类和包: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; ``` 2. 定义请求参数: ``` String url = "http://example.com/api/endpoint"; String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; ``` 3. 设置请求头: ``` Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json; charset=UTF-8"); ``` 4. 创建连接对象并设置请求方法、请求头和请求体: ``` URL object = new URL(url); HttpURLConnection con = (HttpURLConnection) object.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); for (String key : headers.keySet()) { con.setRequestProperty(key, headers.get(key)); } byte[] postData = json.getBytes(StandardCharsets.UTF_8); con.setRequestProperty("Content-Length", String.valueOf(postData.length)); con.getOutputStream().write(postData); ``` 5. 获取响应: ``` int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); ``` 完整代码如下: ``` import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.Map; public class JsonPostRequestExample { public static void main(String[] args) throws Exception { String url = "http://example.com/api/endpoint"; String json = "{\"key1\":\"value1\",\"key2\":\"value2\"}"; Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json; charset=UTF-8"); URL object = new URL(url); HttpURLConnection con = (HttpURLConnection) object.openConnection(); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); for (String key : headers.keySet()) { con.setRequestProperty(key, headers.get(key)); } byte[] postData = json.getBytes(StandardCharsets.UTF_8); con.setRequestProperty("Content-Length", String.valueOf(postData.length)); con.getOutputStream().write(postData); int responseCode = con.getResponseCode(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8)); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("Response Code: " + responseCode); System.out.println("Response Body: " + response.toString()); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值