java - Http 发布请求

标签 java android http url httpwebrequest

我正在开发一个 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!

提前致谢

最佳答案

是的,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);
  }


}

希望这对其他人有帮助

关于java - Http 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24624787/

相关文章:

java - 如何使用 TestNG 测试 expectedExceptionsMessageRegExp(异常消息)?

java - 从群体中移除一条染色体?

android - $http 调用不适用于 Ionic Android 构建

java - Android:下载文件并保存在SD卡上

JavaFX - 阻止用户在不使用 MODAL 的情况下更改阶段

java - LWJGL OpenGL使用纹理图集UV坐标绘制文本

android - 获取adb版本失败;在 Ubuntu 11.10 中错误 = 13

java - 我的 adapter.notifyDataSetChanged() 不工作

android - ImageView的src和背景有什么区别

angular - 在 Angular 项目中将 Http 迁移到 HttpClient