我是android的新手,并尝试通过发送json对象来使用.net weservice。
我正在创建一个json对象并将所有参数添加到它中,如
JSONObject json = new JSONObject();
json.put("name","koli");
json.put("email","asdf@email.com");
在AsyncTask类的doInBackground方法中调用请求
String response = HttpClient.SendHttpPost(params[0],json);
这就是我试图提出请求的方式
public static String SendHttpPost(String URL, JSONObject jsonData) {
Log.d("jsonData", ""+jsonData);
StringBuilder stringBuilder = new StringBuilder();
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(URL);
httpPostRequest.setHeader("User-Agent", "com.altaver.android_PostJson2");
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-Type", "application/json");
StringEntity se = null;
try {
se = new StringEntity(jsonData.toString(),"UTF-8");
se.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
httpPostRequest.setEntity(se);
HttpResponse response = null;
try {
response = client.execute(httpPostRequest);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
在上面的方法中有什么作用
StringEntity se = null;
try {
se = new StringEntity(jsonData.toString(),"UTF-8");
se.setContentType("application/json");
} catch (UnsupportedEncodingException e) {
这个代码片段可以。
为什么我无法发送我的jsonobject?
感谢:)
答案 0 :(得分:2)
在你的doInBackground中尝试这个..
JSONObject jObjOut = null;
try {
HttpPost request = new HttpPost(url);
JSONObject returnedJObject;
returnedJObject = new JSONObject(JSONdata.toString());
JSONStringer json = new JSONStringer();
StringBuilder sb=new StringBuilder();
if (returnedJObject!=null)
{
Iterator<String> itKeys = returnedJObject.keys();
if(itKeys.hasNext())
json.object();
while (itKeys.hasNext())
{
String k=itKeys.next();
json.key(k).value(returnedJObject.get(k));
//Log.e("keys "+k,"value "+returnedJObject.get(k).toString());
}
}
json.endObject();
StringEntity entity;
entity = new StringEntity(json.toString());
entity.setContentType("application/json;charset=UTF-8");
// entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setHeader("Accept", "application/json");
request.setEntity(entity);
HttpResponse response =null;
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 30000);
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(),50000);
response = httpClient.execute(request);
InputStream in;
in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while((line = reader.readLine()) != null){
sb.append(line);
}
return new JSONObject(sb.toString());
答案 1 :(得分:1)
尝试chaging:
se = new StringEntity(jsonData.toString(),"UTF-8");
到此:
se = new StringEntity(jsonData.toString());