【问题标题】:Http Post RequestHttp 发布请求
【发布时间】:2014-07-08 06:09:25
【问题描述】:

我正在开发一个 android 应用程序,它需要向 Web 服务器发送一个字符串(用 java 编写)。当服务器收到这个字符串时,它会自动触发响应。在经历了许多示例后,我尝试这样做。 我使用以下代码发送请求。

try{
                String url = "https://mywebserver";
                URL obj = new URL(url);
                HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

                //add reuqest header
                con.setRequestMethod("POST");

                con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

                String urlParameters = "014500000000000000000000**  0000      0030000100700006800006000000000000000 0     I   00000000        00000000000000000000000000000000000073054721143";

                // Send post request
                con.setDoOutput(true);


                //something is wrong after this line
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();

                int responseCode = con.getResponseCode();


                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                //print result
                System.out.println(response.toString());

            }catch(Exception e){
                tv_str.setText("caught exception");
            }

这不起作用(产生异常)。我也尝试了this example- answer 2 但没有工作 另外,是否有任何用于测试 http post 请求的网络服务器。即我如何测试我的请求

如果有任何其他方法可以做到这一点,请告诉我,因为我是新手

my logcat:

07-08 11:59:37.423: D/dalvikvm(31971): Late-enabling CheckJNI
07-08 11:59:37.713: I/Adreno-EGL(31971): <qeglDrvAPI_eglInitialize:316>: EGL 1.4 QUALCOMM build:  (CL4169980)
07-08 11:59:37.713: I/Adreno-EGL(31971): OpenGL ES Shader Compiler Version: 17.01.10.SPL
07-08 11:59:37.713: I/Adreno-EGL(31971): Build Date: 12/04/13 Wed
07-08 11:59:37.713: I/Adreno-EGL(31971): Local Branch: workspace
07-08 11:59:37.713: I/Adreno-EGL(31971): Remote Branch: 
07-08 11:59:37.713: I/Adreno-EGL(31971): Local Patches: 
07-08 11:59:37.713: I/Adreno-EGL(31971): Reconstruct Branch: 
07-08 11:59:37.764: D/OpenGLRenderer(31971): Enabling debug mode 0
07-08 11:59:37.849: E/Adreno-ES20(31971): <gl_external_unsized_fmt_to_sized:2379>: QCOM> format, datatype mismatch
07-08 11:59:37.849: E/Adreno-ES20(31971): <get_texture_formats:3009>: QCOM> Invalid format!

提前致谢

【问题讨论】:

标签: java android http url httpwebrequest


【解决方案1】:

是的,json 很简单。我实现了这个并且它工作正常.. 感谢 JLONG 和 user1369434。

package m.example.postrwq;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
    Button btnPost;
    TextView tvIsConnected;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnPost = (Button) findViewById(R.id.button1);
        tvIsConnected = (TextView) findViewById(R.id.textView1);

        if(isConnected()){
            tvIsConnected.setBackgroundColor(0xFF00CC00);
            tvIsConnected.setText("You are conncted");
        }
        else{
            tvIsConnected.setText("You are NOT conncted");
        }
    btnPost.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new HttpAsyncTask().execute("http://hmkcode.appspot.com/jsonservlet");
        }});


    }
     private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {



            return POST(urls[0]);
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(getBaseContext(), "Data Sent!", Toast.LENGTH_LONG).show();
       }
    }
public static String POST(String url){
    InputStream inputStream = null;
    String result = "";
    try {

        // 1. create HttpClient
        HttpClient httpclient = new DefaultHttpClient();

        // 2. make POST request to the given URL
        HttpPost httpPost = new HttpPost(url);

        String json = "my string";




     // 6. set json to StringEntity
        StringEntity se = new StringEntity(json);

        // 7. set httpPost Entity
        httpPost.setEntity(se);

        // 8. Set some headers to inform server about the type of the content   
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        // 9. Execute POST request to the given URL
        HttpResponse httpResponse = httpclient.execute(httpPost);

        // 10. receive response as inputStream
        inputStream = httpResponse.getEntity().getContent();

        // 11. convert inputstream to string
        if(inputStream != null)
            result = convertInputStreamToString(inputStream);
        else
            result = "Did not work!";

    } catch (Exception e) {
        Log.d("InputStream", e.getLocalizedMessage());
    }
 // 12. return result
    return result;

}

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    // TODO Auto-generated method stub

    BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
    String line = "";
    String result = "";
    while((line = bufferedReader.readLine()) != null)
        result += line;

    inputStream.close();
    return result;

}
public boolean isConnected() {
    // TODO Auto-generated method stub
     ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
     NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
     if (networkInfo != null && networkInfo.isConnected()) 
         return true;
     else
         return false;  
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
  }


}

希望这对其他人有所帮助

【讨论】:

    【解决方案2】:

    给你一个提示:我认为结合使用 JSON 和 GSON(而不是简单的字符串)在应用程序和网络服务器之间传输数据会更容易。

    【讨论】:

    • 你能帮我一些好的例子或一些代码吗,因为我是安卓新手
    • 您像这样使用 com.google.gson.Gson:public class MySender { //...doing things... final MyDataObject myObj = new MyDataObject("bla", 1, "foo", new Date()); // convert data to JSON with GSON: final String jsonDataStr = new Gson().toJson(myObj); // send JSON somehow: send(jsonDataStr); } public class MyReceiver { // receive somehow JSON from sender: final String jsonData = receive(); // convert JSON back with GSON: final MyDataObject myDataObj = new Gson().fromJson(jsonData, MyDataObject.class); //...work on with your data!... } 抱歉格式不好,无法做得更好:(
    【解决方案3】:

    你真的需要使用HTTPS吗?如果是,我猜你应该在打开它后为你的连接设置SSLSocketFactory。检查此答案以获取更多信息:https://stackoverflow.com/a/16507195/1407451

    我还想建议您不要使用 HttpsURLConnection 本身,而是查看一些用于网络通信的库,例如 RetrofitVolley。对我来说,它似乎更容易使用。

    【讨论】:

      【解决方案4】:

      我使用 JSON 解析器 java 类,因为就像 user1369434 所说的那样,从应用程序和服务器传输数据要容易得多。我忘记了代码是从哪里得到的,但是在这里,创建一个名为 JSONparser 的 java 类,然后发布:

      import java.io.BufferedReader;
      import java.io.IOException;
      import java.io.InputStream;
      import java.io.InputStreamReader;
      import java.io.UnsupportedEncodingException;
      import java.util.List;
      
      import org.apache.http.HttpEntity;
      import org.apache.http.HttpResponse;
      import org.apache.http.NameValuePair;
      import org.apache.http.client.ClientProtocolException;
      import org.apache.http.client.entity.UrlEncodedFormEntity;
      import org.apache.http.client.methods.HttpGet;
      import org.apache.http.client.methods.HttpPost;
      import org.apache.http.client.utils.URLEncodedUtils;
      import org.apache.http.impl.client.DefaultHttpClient;
      import org.json.JSONException;
      import org.json.JSONObject;
      
      import android.util.Log;
      
      public class JSONParser {
      
          static InputStream is = null;
          static JSONObject jObj = null;
          static String json = "";
      
          // constructor
          public JSONParser() {
      
          }
      
          // function get json from url
          // by making HTTP POST or GET mehtod
          public JSONObject makeHttpRequest(String url, String method,
                  List<NameValuePair> params) {
      
              // Making HTTP request
              try {
      
                  // check for request method
                  if(method == "POST"){
                      // request method is POST
                      // defaultHttpClient
                      DefaultHttpClient httpClient = new DefaultHttpClient();
                      HttpPost httpPost = new HttpPost(url);
                      httpPost.setEntity(new UrlEncodedFormEntity(params));
      
                      HttpResponse httpResponse = httpClient.execute(httpPost);
                      HttpEntity httpEntity = httpResponse.getEntity();
                      is = httpEntity.getContent();
      
                  }else if(method == "GET"){
                      // request method is GET
                      DefaultHttpClient httpClient = new DefaultHttpClient();
                      String paramString = URLEncodedUtils.format(params, "utf-8");
                      url += "?" + paramString;
                      HttpGet httpGet = new HttpGet(url);
      
                      HttpResponse httpResponse = httpClient.execute(httpGet);
                      HttpEntity httpEntity = httpResponse.getEntity();
                      is = httpEntity.getContent();
                  }           
      
      
              } catch (UnsupportedEncodingException e) {
                  e.printStackTrace();
              } catch (ClientProtocolException e) {
                  e.printStackTrace();
              } catch (IOException e) {
                  e.printStackTrace();
              }
      
              try {
                  BufferedReader reader = new BufferedReader(new InputStreamReader(
                          is, "iso-8859-1"), 8);
                  StringBuilder sb = new StringBuilder();
                  String line = null;
                  while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");
                  }
                  is.close();
                  json = sb.toString();
              } catch (Exception e) {
                  Log.e("Buffer Error", "Error converting result " + e.toString());
              }
      
              // try parse the string to a JSON object
              try {
                  jObj = new JSONObject(json);
              } catch (JSONException e) {
                  Log.e("JSON Parser", "Error parsing data " + e.toString());
              }
      
              // return JSON String
              return jObj;
      
          }
      }
      

      然后在您的 Activty 上执行此操作:

          public class YOUR ACTIVITY extends Activity {
      
              JSONParser jParser = new JSONParser();
      
              @Override
              public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
      
                  //Create a Asynctask for the http request
                  new NAMEOFYOURASYNCTASK().execute();
      
      }
      
          }
      

      在你的异步任务上:

      class YOURASYNCTASK extends AsyncTask<String, String, String> {
      
      @Override
      protected String doInBackground(String... args) {
          // TODO Auto-generated method stub
          // Building Parameters
          List<NameValuePair> params = new ArrayList<NameValuePair>();
          params.add(new BasicNameValuePair("username_GET", dealer_user_name ));
      
          // getting JSON string from URL
          json = jParser.makeHttpRequest(YOUR URL HERE, "POST", params);
      
          // Check your log cat for JSON reponse
          Log.d("All Products: ", json.toString());
      

      修改您的 php 代码以将 JSON 文件返回到应用程序和。像这样:

          // array for JSON response
          $response = array();
          // success
          $response["success"] = 1;
          // echoing JSON response
          echo json_encode($response);
      

      你明白了。顺便说一句,这只是一个建议。

      【讨论】:

      • 感谢代码和帮助,但我想在这里发送一个字符串而不是 所以我该怎么做
      • 正如我所说,我的服务器是用 java 而不是 php 配置的。
      • 嗯,我不知道 java 配置的服务器,但我认为这个有帮助。 stackoverflow.com/questions/11305773/… 但是在将json解析到服务器时,我向您展示的json解析器类应该向服务器发送一个字符串。我正在使用此类将数据解析到我的服务器,所以在 params.add(new BasicNameValuePair("username_GET", YOUR STRING HERE ));所以在服务器端,你可以通过调用 username_GET 来获取应用发送的数据。
      猜你喜欢
      • 2021-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 2012-07-06
      • 1970-01-01
      相关资源
      最近更新 更多