Android HttpClient、DefaultHttpClient、HttpPost
如何将字符串数据(Android HttpClient、DefaultHttpClient、HttpPost,android,apache-httpclient-4.x,Android,Apache Httpclient 4.x,如何将字符串数据(JSONObject.toString())发送到url。我想在util类中编写一个静态方法来实现这一点。我希望方法签名如下 publicstaticstringpostdata(stringurl,stringpostdata)抛出一些CustomException 字符串url的格式应该是什么 返回字符串是来自服务器的响应,作为json数据的字符串表示 编辑 当前连接util 对数输出 10-16 11:27:27.287:E/log_标记(4935):http连接java
JSONObject.toString()
)发送到url。我想在util类中编写一个静态方法来实现这一点。我希望方法签名如下
publicstaticstringpostdata(stringurl,stringpostdata)抛出一些CustomException
字符串url的格式应该是什么
返回字符串是来自服务器的响应,作为json数据的字符串表示
编辑
当前连接util
对数输出
10-16 11:27:27.287:E/log_标记(4935):http连接java.lang.NullPointerException中出错
10-16 11:27:27.287:W/System.err(4935):java.lang.NullPointerException
10-16 11:27:27.287:W/System.err(4935):位于org.apache.http.impl.client.AbstractHttpClient.DeterminateTarget(AbstractHttpClient.java:496)
10-16 11:27:27.307:W/System.err(4935):位于org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-16 11:27:27.327:W/System.err(4935):位于org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-16 11:27:27.327:W/System.err(4935):位于in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92)
10-16 11:27:27.327:W/System.err(4935):在in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:54)
10-16 11:27:27.327:W/System.err(4935):在in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:1)
10-16 11:27:27.327:W/System.err(4935):位于android.os.AsyncTask$2.call(AsyncTask.java:185)
10-16 11:27:27.327:W/System.err(4935):在java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
10-16 11:27:27.327:W/System.err(4935):位于java.util.concurrent.FutureTask.run(FutureTask.java:138)
10-16 11:27:27.327:W/System.err(4935):位于java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
10-16 11:27:27.327:W/System.err(4935):位于java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
10-16 11:27:27.327:W/System.err(4935):位于java.lang.Thread.run(Thread.java:1019)
10-16 11:27:27.327:V/log_标记(4935):无法建立网络连接
尝试使用此方法,其中strJsonRequest是要发布的json字符串,strUrl是要发布strJsonRequest的url
public String urlPost(String strJsonRequest, String strURL) throws Exception
{
try
{
URL objURL = new URL(strURL);
connection = (HttpURLConnection)objURL.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setAllowUserInteraction(false);
connection.setUseCaches(false);
connection.setConnectTimeout(TIMEOUT_CONNECT_MILLIS);
connection.setReadTimeout(TIMEOUT_READ_MILLIS);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept-Charset", "utf-8");
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");
connection.setRequestProperty("Content-Length", ""+strJsonRequest.toString().getBytes("UTF8").length);
DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
byte [] b = strJsonRequest.getBytes("UTF-8");
outputStream.write(b);
outputStream.flush();
inputstreamObj = (InputStream) connection.getContent();//getInputStream();
if(inputstreamObj != null)
strResponse = convertStreamToString(inputstreamObj);
}
catch(Exception e)
{
throw e;
}
return strResponse;
}
方法convertStreamToString()如下所示
private static String convertStreamToString(InputStream is)
{
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(is));
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
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();
}
根据服务器端代码的设置方式,服务器有一个php页面来处理API调用的url的示例格式如下:
http://yoururl.com/demo.php?jsondata=postData
如果您使用的是post连接,您可以简单地说:
http://yoururl.com/demo.php
并将post参数(即json字符串)传递给它
以下是有关如何执行此操作的精彩教程:
好吧,以下是我对你的问题的看法:-
POST
方法将数据发送到服务器。在安卓系统中,这也很容易而且绝对可行。用于发送POST
数据的简单代码段如下:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://yourserverIP/postdata.php");
String serverResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("datakey1", dataValue1));
nameValuePairs.add(new BasicNameValuePair("datakey2",
dataValue2));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
serverResponse = response.getStatusLine().toString();
Log.e("response", serverResponse);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
希望这有帮助。谢谢。我认为在您的代码中,基本问题是由您使用
StringEntity
将参数发布到url的方式造成的。检查以下代码是否有助于使用StringEntity
将数据发布到服务器
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("data", dataValue);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
希望这有助于解决您的问题。谢谢。服务器接受post连接。所以我只需要像http://www.example.com/my_page.php
,对吗?什么是方法converStreamToString
?url格式应该是什么?我收到一个MalformedURLException
我不确定您在logcat中得到的url是什么,检查一下它是否与您通过的url相同我没有使用表单。服务器只想查看字符串数据。仅此而已。@phodu_insaan即使要发送字符串数据,也需要将POST数据发送到服务器。因此,不需要使用表单将字符串数据发送到服务器。如果您只是想发送命令,比如只向服务器传递一个参数,那么您也可以考虑使用GET方法。我也可以帮你,我也在做同样的事情。我不是传递UrlEncodedFormEntity
而是传递带有字符串数据的新StringEntity
。我得到一个NullPointerException
。只是在问题后面加上我的logcat输出。是的,请在这里加上你的logcat输出。。而我无法得到你,你是如何通过一个实体??请同时添加执行此任务的代码。。这将有助于更好地理解您的问题..我认为您的POST方法将StringEntity发送到服务器端时存在一些问题。。看看我的最新答案,看看它是否有效。我认为这有帮助,但我仍然得到一个运行时错误UnknownHostException。我确信我的url是有效的,并通过浏览器进行了检查。我在google.com或example.com上也遇到了同样的错误。我应该如何格式化URL/URI?我想点击网址http://xyz.mysite.com/some_page.php/
和post数据。是否还需要指定端口?仅使用80。所以这应该是默认的。这项功能现在正在运行,并正在访问服务器。非常感谢。
String jsonData = EntityUtils.toString(serverResponse.getEntity());
// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("data", dataValue);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);