如何解析web服务和使用POST方法在android系统发布的数据? [英] How to parse the webservice and use post method to post data in android?

查看:132
本文介绍了如何解析web服务和使用POST方法在android系统发布的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  =一个JSONObjects {
         PROJID:78,
         UID:1,
         EMAILID:test@yahoo.com
         ProjectInviterFQAnswer:[{
             slno:1,
             答案:A1,
             序:1
             标记:F
         },{
             slno:2,
             答案:A1,
             序:2
             标记:F
         },{
             slno:1,
             答案:A1,
             序:2
             旗帜:Q
         }
          ]
       };

我上面的web服务,现在我想将数据发布此WebService在关键的答案。我如何解析和投入答案我的钥匙串阵?

我的code如下。但它给响应,出现了一个错误。

  @覆盖
         保护字符串doInBackground(字符串的URL ...){
        HttpClient的HttpClient的=新DefaultHttpClient();
        HttpContext的背景下=新BasicHttpContext();
        HttpPost httpPost =新HttpPost(URL);
        JSONObject的JSON =新的JSONObject();
        httpPost.setHeader(内容类型,
                        应用/ JSON的;字符集= UTF-8);        尝试{            //json.put(\"EmailID\",\"test@yahoo.com);
            //json.put(\"ProjID\",\"78);
            //json.put(\"UID,1);
            //json.put(\"ProjectInviterFQAnswer,对象);
            StringEntity stringEntity =新StringEntity(json.toString());
            InputStream的流=新
ByteArrayInputStream进行(json.toString()的getBytes(UTF-8)。);
            httpPost.setEntity(新StringEntity(json.toString()));
            HTT presponse HTT presponse = httpClient.execute(httpPost,背景);
            读者的BufferedReader =新的BufferedReader(新的InputStreamReader(HTT presponse.getEntity()的getContent(),UTF-8));
            RES = reader.readLine();
            RESP = res.toString();
            Log.e(响应WEBSER的:RESP);
        }赶上(UnsupportedEncodingException五){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(ClientProtocolException E){
            // TODO自动生成catch块
            e.printStackTrace();
        }赶上(IOException异常五){
            // TODO自动生成catch块
            e.printStackTrace();
        }        返回水库;


解决方案

以一个的ArrayList 的NameValuePair <​​/ code>为例如
的ArrayList&LT;&的NameValuePair GT; postParameters =新的ArrayList&LT;&的NameValuePair GT;();

然后添加您的paramters在接听键如下:

  postParameters.add(新BasicNameValuePair(答案,
                        你的价值));
                串响应=无效;
                尝试{
                    响应= CustomHttpClient
                            .executeHttpPost(
                                    您的网址,postParameters);`

CustomHTTPClientmethod

 公共类CustomHttpClient {/ **所花费的时间为我们的客户超时* /
公共静态最终诠释HTTP_TIMEOUT = 30 * 1000; //毫秒
/ **我们的HttpClient单实例* /
私有静态HttpClient的mHttpClient;/ **
 *获取我们的HttpClient我们对象的单个实例。
 *
 返回:一个HttpClient的对象,连接参数设置
 * /私有静态HttpClient的getHttpClient(){    如果(mHttpClient == NULL){
        mHttpClient =新DefaultHttpClient();        最终的HttpParams PARAMS = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(参数,可以HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(参数,可以HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(参数,可以HTTP_TIMEOUT);
    }    返回mHttpClient;
}/ **
 *执行一个HTTP POST请求与指定指定的网址
 *参数。
 *
 * @参数网址
 *该网址张贴请求
 * @参数postParameters
 *参数通过发送请求
 返回:请求的结果
 * @throws异常
 * /公共静态字符串executeHttpPost(字符串URL,
        ArrayList的&LT;&的NameValuePair GT; postParameters)抛出异常{    在的BufferedReader = NULL;    尝试{        HttpClient的客户= getHttpClient();        HttpPost要求=新HttpPost(URL);        UrlEn codedFormEntity formEntity =新UrlEn codedFormEntity(        postParameters);        request.setEntity(formEntity);        HTT presponse响应= client.execute(请求);        在=新的BufferedReader(新的InputStreamReader(response.getEntity()        .getContent()));        StringBuffer的SB =新的StringBuffer();        串线=;        串NL = System.getProperty(line.separator);        而((行= in.readLine())!= NULL){            sb.append(行+ NL);        }        附寄();        字符串结果= sb.toString();        返回结果;    } {最后        如果(在!= NULL){            尝试{                附寄();            }赶上(IOException异常五){                Log.e(log_tag,错误转换结果+ e.toString());                e.printStackTrace();            }        }    }}
 }

希望这可以解决你所要求的。

      jsonObjects = {
         "ProjID": "78",
         "Uid": "1",
         "EmailID": "test@yahoo.com",
         "ProjectInviterFQAnswer": [{
             "slno": "1",
             "Answer": "a1",
             "order": "1",
             "flag": "F"
         }, {
             "slno": "2",
             "Answer": "a1",
             "order": "2",
             "flag": "F"
         }, {
             "slno": "1",
             "Answer": "a1",
             "order": "2",
             "flag": "Q"
         }
          ]
       };

I have the above webservice, and now I want to post data to this webservice in the key "answer". How can I parse and put my array string in "answer" key?

my code is as follows. but it gives response as An error has occured..

     @Override
         protected String doInBackground(String... urls) {
        HttpClient httpClient= new DefaultHttpClient();
        HttpContext context=new BasicHttpContext();
        HttpPost httpPost=new HttpPost(url);
        JSONObject json=new JSONObject();
        httpPost.setHeader("Content-type",
                        "application/json; charset=UTF-8");

        try {

            //json.put("EmailID","test@yahoo.com");
            //json.put("ProjID","78");
            //json.put("UID", "1");
            //json.put("ProjectInviterFQAnswer", "Object");
            StringEntity stringEntity = new StringEntity(json.toString());
            InputStream stream= new  
ByteArrayInputStream(json.toString().getBytes("UTF-8"));
            httpPost.setEntity(new StringEntity(json.toString()));
            HttpResponse httpResponse= httpClient.execute(httpPost,context);
            BufferedReader reader= new BufferedReader(new    InputStreamReader(httpResponse.getEntity().getContent(),"UTF-8"));
            res= reader.readLine();
            resp=res.toString();
            Log.e("RESPONSE OF WEBSER:", resp);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return res;

解决方案

Take an ArrayList of NameValuePair for e.g ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

then add your paramters in the answer key as follows

postParameters.add(new BasicNameValuePair("answer",
                        "Your value"));
                String response = null;
                try {
                    response = CustomHttpClient
                            .executeHttpPost(
                                    "Your Url", postParameters);`

CustomHTTPClientmethod

 public class CustomHttpClient {

/** The time it takes for our client to timeout */
public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds
/** Single instance of our HttpClient */
private static HttpClient mHttpClient;

/**
 * Get our single instance of our HttpClient object.
 * 
 * @return an HttpClient object with connection parameters set
 */

private static HttpClient getHttpClient() {

    if (mHttpClient == null) {
        mHttpClient = new DefaultHttpClient();

        final HttpParams params = mHttpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
        ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }

    return mHttpClient;
}

/**
 * Performs an HTTP Post request to the specified url with the specified
 * parameters.
 * 
 * @param url
 *            The web address to post the request to
 * @param postParameters
 *            The parameters to send via the request
 * @return The result of the request
 * @throws Exception
 */

public static String executeHttpPost(String url,
        ArrayList<NameValuePair> postParameters) throws Exception {

    BufferedReader in = null;

    try {

        HttpClient client = getHttpClient();

        HttpPost request = new HttpPost(url);

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(

        postParameters);

        request.setEntity(formEntity);

        HttpResponse response = client.execute(request);

        in = new BufferedReader(new InputStreamReader(response.getEntity()

        .getContent()));

        StringBuffer sb = new StringBuffer("");

        String line = "";

        String NL = System.getProperty("line.separator");

        while ((line = in.readLine()) != null) {

            sb.append(line + NL);

        }

        in.close();

        String result = sb.toString();

        return result;

    } finally {

        if (in != null) {

            try {

                in.close();

            } catch (IOException e) {

                Log.e("log_tag", "Error converting result " + e.toString());

                e.printStackTrace();

            }

        }

    }

}
 }

Hope this solves what you are asking for ..

这篇关于如何解析web服务和使用POST方法在android系统发布的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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