gpt4 book ai didi

java - 如何使用REST将Json字符串发送到android参数中的java webservice?

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:12 24 4
gpt4 key购买 nike

恶魔,我将带有三个参数的 JSON 字符串发送到 java web 服务方法。但在java端方法无法在控制台中打印。请指导我必须从下面的代码中更改什么?

String json = "";
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
HttpClient httpclient = new DefaultHttpClient();

// Prepare a request object
HttpPost httpPost = new HttpPost(url);
HttpGet httpGet = new HttpGet(url);

JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("name", "ghanshyam");
jsonObject.put("country", "India");
jsonObject.put("twitter", "ghahhd");

json = jsonObject.toString();

StringEntity se = new StringEntity(json);

se.setContentEncoding("UTF-8");
se.setContentType("application/json");

// 6. set httpPost Entity
System.out.println(json);

httpPost.setEntity(se);
httpGet.se
// 7. Set some headers to inform server about the type of the content
//httpPost.addHeader( "SOAPAction", "application/json" );
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");

//String s = doGet(url).toString();

Toast.makeText(getApplicationContext(), "Data Sent", Toast.LENGTH_SHORT).show();

最佳答案

使用以下代码将 json 发布到 Java Web 服务:并以字符串形式获取响应。

    JSONObject json = new JSONObject();
json.put("name", "ghanshyam");
json.put("country", "India");
json.put("twitter", "ghahhd");

HttpPost post = new HttpPost(url);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse httpresponse = client.execute(post);
HttpEntity entity = httpresponse.getEntity();
InputStream stream = entity.getContent();
String result = convertStreamToString(stream);

你的convertStremToString()方法将如下:

    public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try
{
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return sb.toString();
}

关于java - 如何使用REST将Json字符串发送到android参数中的java webservice?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22936367/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com