Android的HttpClient的,DefaultHttpClient,HttpPost [英] Android HttpClient, DefaultHttpClient, HttpPost

查看:144
本文介绍了Android的HttpClient的,DefaultHttpClient,HttpPost的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么会发送一个字符串数据( JSONObject.toString())到URL。我想写一个UTIL类的静态方法来做到这一点。我想方法签名是如下:

公共静态字符串POSTDATA(URL字符串,字符串POSTDATA)抛出SomeCustomException

字符串的URL应该是什么格式

则返回的字符串是从服务器中作为一个字符串重新JSON数据presentation响应。

修改

present UTIL

连接

 包my.package;
进口my.package.exceptions.CustomException;

进口java.io.BufferedReader中;
进口的java.io.InputStream;
进口java.io.InputStreamReader中;
进口java.net.URLDe codeR;

进口org.apache.http.HttpEntity;
进口org.apache.http.Htt presponse;
进口org.apache.http.client.HttpClient;
进口org.apache.http.client.methods.HttpGet;
进口org.apache.http.client.methods.HttpPost;
进口org.apache.http.entity.StringEntity;
进口org.apache.http.impl.client.DefaultHttpClient;


 公共类ConnectionUtil {

 公共静态字符串POSTDATA(URL字符串,字符串POSTDATA)
        抛出CustomException {

    //创建一个新的HttpClient和门柱头球
    InputStream的是= NULL;
    StringBuilder的SB = NULL;
    字符串结果=;
    HttpClient的HttpClient的=新DefaultHttpClient();

HttpPost httppost =新HttpPost();
    httppost.setHeader(主机,网址);

    Log.v(ConnectionUtil,开放的POST连接到URI =+ httppost.getURI()+URL =+ URLDe coder.de code(URL));

    尝试 {
        httppost.setEntity(新StringEntity(POSTDATA));

        //执行HTTP POST请求
        HTT presponse响应= httpclient.execute(httppost);
        HttpEntity实体= response.getEntity();
        是= entity.getContent();

    }赶上(例外五){
        Log.e(log_tag,错误的HTTP连接+ e.toString());
        e.printStackTrace();
        抛出新CustomException(无法建立网络连接);
    }
    尝试 {
        的BufferedReader读卡器=新的BufferedReader(新的InputStreamReader(
                是,UTF-8),8);
        SB =新的StringBuilder();
        sb.append(reader.readLine()+\ N);
        串行=0;

        而((行= reader.readLine())!= NULL){
            sb.append(行+\ N);
        }

        is.close();
        结果= sb.toString();

    }赶上(例外五){
        Log.e(log_tag,错误转换结果+ e.toString());
        抛出新CustomException(错误解析响应);
    }
    Log.v(ConnectionUtil,发送:+ POSTDATA);
    Log.v(ConnectionUtil,得到结果+结果);
    返回结果;

}

}
 

的logcat输出

十一月一十号至16号:27:27.287:E / log_tag(4935):在HTTP连接显示java.lang.NullPointerException错误 十一月一十号至16号:27:27.287:W / System.err的(4935):显示java.lang.NullPointerException 十一月一十号至16号:27:27.287:W / System.err的(4935):在org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496) 十一月一十号至16号:27:27.307:W / System.err的(4935):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 十一月一十号至16号:27:27.327:W / System.err的(4935):在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 十一月一十号至16号:27:27.327:W / System.err的(4935):在in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92) 十一月一十号至16号:27:27.327:W / System.err的(4935):在in.gharpay.zap.integration.ZapTransaction $ 1.doInBackground(ZapTransaction.java:54) 十一月一十号至16号:27:27.327:W / System.err的(4935):在in.gharpay.zap.integration.ZapTransaction $ 1.doInBackground(ZapTransaction.java:1) 十一月一十号至16号:27:27.327:W / System.err的(4935):在android.os.AsyncTask $ 2.call(AsyncTask.java:185) 十一月一十号至16号:27:27.327:W / System.err的(4935):在java.util.concurrent.FutureTask中$ Sync.innerRun(FutureTask.java:306) 十一月一十号至16号:27:27.327:W / System.err的(4935):在java.util.concurrent.FutureTask.run(FutureTask.java:138) 十一月一十号至16号:27:27.327:W / System.err的(4935):在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 十一月一十号至16号:27:27.327:W / System.err的(4935):在java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:581) 十一月一十号至16号:27:27.327:W / System.err的(4935):在java.lang.Thread.run(Thread.java:1019) 十一月一十号至16号:27:27.327:V / log_tag(4935):无法建立网络连接
解决方案

我想在$ C C的基本问题$是由您所使用的方法 StringEntity POST 参数的URL。检查是否以下code有助于使用发布您的数据到服务器 StringEntity

  //构建JSON对象来传递参数
    JSONObject的jsonObj =新的JSONObject();
    jsonObj.put(用户名,用户名);
    jsonObj.put(数据,dataValue);

    //创建POST对象,并添加参数
    HttpPost httpPost =新HttpPost(URL);
    StringEntity实体=新StringEntity(jsonObj.toString(),HTTP.UTF_8);
    entity.setContentType(应用/ JSON);
    httpPost.setEntity(实体);

    HttpClient的客户端=新DefaultHttpClient();
    HTT presponse响应= client.execute(httpPost);
 

希望这有助于解决您的问题。谢谢你。

How would I send a string data (JSONObject.toString()) to a url. I want to write a static method in a util class to do this. I want the method signature to be as follows

public static String postData (String url, String postData) throws SomeCustomException

What should be the format of the string url

The return String is the response from the server in as a string representation of json data.

EDIT

Present connection util

package my.package;
import my.package.exceptions.CustomException;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;


 public class ConnectionUtil {

 public static String postData(String url, String postData)
        throws CustomException {

    // Create a new HttpClient and Post Header
    InputStream is = null;
    StringBuilder sb = null;
    String result = "";
    HttpClient httpclient = new DefaultHttpClient();

HttpPost httppost = new HttpPost();
    httppost.setHeader("host", url);

    Log.v("ConnectionUtil", "Opening POST connection to URI = " + httppost.getURI() + " url = " + URLDecoder.decode(url));

    try {
        httppost.setEntity(new StringEntity(postData));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
        e.printStackTrace();
        throw new CustomException("Could not establish network connection");
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line = "0";

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        result = sb.toString();

    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
        throw new CustomException("Error parsing the response");
    }
    Log.v("ConnectionUtil", "Sent: "+postData);
    Log.v("ConnectionUtil", "Got result "+result);
    return result;

}

}

Logcat output

10-16 11:27:27.287: E/log_tag(4935): Error in http connection 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): at org.apache.http.impl.client.AbstractHttpClient.determineTarget(AbstractHttpClient.java:496) 10-16 11:27:27.307: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 10-16 11:27:27.327: W/System.err(4935): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ConnectionUtil.postData(ConnectionUtil.java:92) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:54) 10-16 11:27:27.327: W/System.err(4935): at in.gharpay.zap.integration.ZapTransaction$1.doInBackground(ZapTransaction.java:1) 10-16 11:27:27.327: W/System.err(4935): at android.os.AsyncTask$2.call(AsyncTask.java:185) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.FutureTask.run(FutureTask.java:138) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088) 10-16 11:27:27.327: W/System.err(4935): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581) 10-16 11:27:27.327: W/System.err(4935): at java.lang.Thread.run(Thread.java:1019) 10-16 11:27:27.327: V/log_tag(4935): Could not establish network connection

解决方案

I think in your code the basic problem is caused by the way you are using StringEntity to POST parameters to your url. Check to see if the following code helps in posting your data to the server using 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);

Hope this helps in solving your problem. Thanks.

这篇关于Android的HttpClient的,DefaultHttpClient,HttpPost的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆