如何解析web服务并使用post方法在android中发布数据?

时间:2013-11-01 05:47:13

标签: android web-services

      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"
         }
          ]
       };

我有上述网络服务,现在我想在关键字“回答”中将数据发布到此网络服务。如何解析并将我的数组字符串放入“answer”键?

我的代码如下。但它会在出现错误时给出响应..

     @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;

2 个答案:

答案 0 :(得分:0)

ArrayList NameValuePair为例 ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();

然后在答案键中添加您的参数,如下所示

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

CustomHTTPClient方法

 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();

            }

        }

    }

}
 }

希望这能解决你所要求的......

答案 1 :(得分:0)

我试着解决这里是我的代码。

首先在gradle中添加依赖

编译'com.squareup.okhttp:okhttp:2.6.0'

编译'com.google.code.gson:gson:2.2.4'

<强> Parser.java

<?php
    $str = 9010201;
    echo strrev(trim(chunk_split(strrev($str),2,' ')));
?>

并致电 Parser.java

    public class Parser extends AsyncTask<Void, Void, Boolean> {

            private Activity activity;
            private String type = "";
            private String url = "";
            private RequestBody parameter;
            private Boolean success = true;
            private int requestCode = 0;
            private boolean isShowProgressDialog = true;
            private ProgressDialog progressDialog;
            private String jsonResponse = "";
            public GetResponse getResponse = null;
            private boolean cancel = false;
            private boolean isJsonRequest;


            public Parser(Activity activity, String type, String url, RequestBody parameter,boolean isShowProgressDialog,int requestCode) {
                this.activity = activity;
                this.type = type;
                this.url = url;
                cancel = false;
                this.parameter = parameter;
                this.isShowProgressDialog = isShowProgressDialog;
                this.requestCode = requestCode;
                if (isShowProgressDialog) {
                    progressDialog = new ProgressDialog(activity);
                }
            }

            /**
             * @purpose : this constructor is called when get api called.
             * @param activity
             * @param type
             * @param url
             * @param isShowProgressDialog
             * @param requestCode
             */
            public Parser(Activity activity, String type, String url, boolean isShowProgressDialog, int requestCode) {
                this.activity = activity;
                this.type = type;
                this.url = url;
                cancel = false;
                this.isShowProgressDialog = isShowProgressDialog;
                this.requestCode = requestCode;
                if (isShowProgressDialog) {
                    progressDialog = new ProgressDialog(activity);
                }

            }

            public interface GetResponse {
                void TaskFinish(String response, int request, boolean success);
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                if (isShowProgressDialog) {
                    progressDialog.setTitle("Loading");
                    progressDialog.setMessage("Please wait");
                    progressDialog.setCancelable(false);
                    progressDialog.show();
                }
            }

            @Override
            protected Boolean doInBackground(Void... voids) {
                if (Common.isOnline(activity)) {
                    try {
                        if (type.equalsIgnoreCase(Constant.Type.post)) {
                            jsonResponse = doPostResponse();
                        } else if (type.equalsIgnoreCase(Constant.Type.get)) {
                            jsonResponse = doGetResponse();
                        }
                        success = true;
                    } catch (Exception exp) {
                        exp.printStackTrace();
                        success = false;
                    }
                    return success;
                } else {
                    success = false;
                    return success;
                }

            }

            @Override
            protected void onPostExecute(Boolean result) {
                if (cancel) {
                    cancel = false;
                } else {
                    if (!result) {
                        if (isShowProgressDialog) {
                            if (this.progressDialog.isShowing()) {
                                this.progressDialog.dismiss();
                            }
                        }
                    } else {
                        if (isShowProgressDialog) {
                            if (this.progressDialog.isShowing()) {
                                this.progressDialog.dismiss();
                            }
                        }

                        if (getResponse != null) {

                            getResponse.TaskFinish(jsonResponse, requestCode, success);
                        } else {
                            Log.i("ApiAccess", "You have not assigned IApiAccessResponse delegate");
                        }
                    }
                }
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();

                if (isShowProgressDialog) {
                    getResponse.TaskFinish(jsonResponse, requestCode, success);
                    if (progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                }
                success = false;
                cancel = true;
            }

            private String doPostResponse() {

                OkHttpClient okHttpClient = new OkHttpClient();
                Response response;
                String mResponse = "";
                try {
                    Request request = new Request.Builder()
                            .url(url)
                            .post(parameter)
                            .build();

                    okHttpClient.setConnectTimeout(90, TimeUnit.SECONDS);
                    okHttpClient.setReadTimeout(90, TimeUnit.SECONDS);
                    okHttpClient.setWriteTimeout(90, TimeUnit.SECONDS);

                    response = okHttpClient.newCall(request).execute();
                    mResponse = response.body().string();
                    Log.i("model.Response Post", "" + mResponse);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }


                return mResponse;
            }

            private String doGetResponse() {
                OkHttpClient okHttpClient = new OkHttpClient();

                Response response;
                String mResponse = "";
                try {
                    Request request = new Request.Builder()
                            .url(url)
                            .build();
                    response = okHttpClient.newCall(request).execute();
                    mResponse = response.body().string();
                    Log.i("model.Response Get", "" + mResponse);
                } catch (Exception exp) {
                    exp.printStackTrace();
                }

                return mResponse;
            }

            public void setjsonRequest(boolean isjsonRequest) {
                this.isJsonRequest = isjsonRequest;
            }

        }

将文件转换为byte的方法。

  public class Login extends AppCompatActivity implements View.OnClickListener, Parser.GetResponse{

                    private EditText edtEmailId;
                    private EditText edtPassword;
                    private Button btnSubmit;
                    @Override
                    protected void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.login);
                        findViews();

                    }
                    public void findViews() {
                        edtEmailId = (EditText) findViewById(R.id.edtEmailId);
                        edtPassword = (EditText) findViewById(R.id.edtPassword);
                        btnSubmit = (Button) findViewById(R.id.btnSubmit);
                        btnSubmit.setOnClickListener(this);
                    }

                    @Override
                    public void onClick(View view) {

                        switch (view.getId()) {
                            case R.id.btnSubmit:
                                callRegistration();
                                break;

                            default:
                                break;
                        }
                    }


                    private void callRegistration(){
                        /*RequestBody formBody = new FormEncodingBuilder()
                                .add("email_id", edtEmailId.getText().toString().trim())
                                .add("password", edtPassword.getText().toString().trim())
                                .build();*/
 File filePath1 = new File("image1.jpg");
 MultipartBuilder multipartBuilder;
        multipartBuilder = new MultipartBuilder()
                .type(MultipartBuilder.FORM)
                .addFormDataPart(Constant.emailId, edtEmailId.getText().toString().trim())
                .addFormDataPart(Constant.password, edtPassword.getText().toString().trim());

//send image to server using multipart
 multipartBuilder.addFormDataPart(Constant.docDriverLicenceFront, filePath1.getName(), RequestBody.create(MediaType.parse("image/jpeg"), Common.convertFileToByte(filePath1)));
                RequestBody formBody = multipartBuilder.build();
                        Parser parser=new Parser(this, Constant.Type.post,Constant.Url.SIGN_IN,formBody,true,0);
                        parser.setjsonRequest(false);
                        parser.getResponse = this;
                        parser.execute();

                    }


                    @Override
                    public void TaskFinish(String response, int request, boolean success) {

                        if(request==0){
                            handleResponse(response);
                        }
                    }

                    private void handleResponse(String output) {
                         AppLog.LogI(TAG, output);
                    final Gson gson = new Gson();
                    try {
                        SignUpModel login = gson.fromJson(output, SignUpModel.class);
                        if (login != null) {
                            if (login.status.equalsIgnoreCase("1")) {
                                AppLog.LogI(TAG, "Success");
                                //final LoginModel instance = setLoginModel(login);
                                //SignUpModel.getInstance().getEmailId();
                                //Common.passIntent(ThankYouActivity.this, SignInActivity.class);
                                Toast.makeText(this, "" + login.message, Toast.LENGTH_SHORT).show();
                                Common.passIntent(this, SignInActivity.class);
                                finish();
                            } else {
                                Toast.makeText(this, "" + login.message, Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (Exception e) {
                        Common.displayToast(ThankYouActivity.this, getResources().getString(R.string.str_something_went_worng));
                    }
                }

                    }
                }