从android发送http帖子

时间:2013-12-17 12:16:11

标签: java android

我有一个用python编写的服务器,它读取querystring-message并将其存储在sqlite数据库中,然后显示内容。

现在我想从Android应用程序发送消息。到目前为止,这是我的代码。

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {

Button send;
TextView display;
String message;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    send = (Button)findViewById(R.id.button1);
    display = (TextView)findViewById(R.id.editText1);


    send.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            try{
                post();
            }
            catch(Exception e)
            {
                display.setText("Det sket sig");

            }

        }

        public void post() throws  UnsupportedEncodingException
        {
            message = display.getText().toString();
            String data = URLEncoder.encode("?message", "UTF-8") 
                    + "=" + URLEncoder.encode(message, "UTF-8");

            String text = "";
            BufferedReader reader=null;

            try
            {
                URL url = new URL("http:homepage.net");

                URLConnection conn = url.openConnection(); 
                conn.setDoOutput(true); 
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream()); 
                wr.write(data); 
                wr.flush(); 

                reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line = null;

                while((line = reader.readLine()) != null)
                {
                       sb.append(line + "\n");
                }
                text = sb.toString();
            }
            catch(Exception e)
            {

            }
            finally
            {
                try
                {
                    reader.close();
                }

                catch(Exception ex) {}
            }
            display.setText(text);
        }
    });


}

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

}

这不符合预期。我在这做错了什么?

5 个答案:

答案 0 :(得分:0)

对于网络相关操作,您必须使用asynctask或线程,否则您将获得NetworkOnMainThreadException。 参考here

private class MyTask extends AsyncTask<Void, Void, Void> { ... }

答案 1 :(得分:0)

使用以下AsyncTask发出服务器请求:

public class RestServiceTask extends AsyncTask<String, Void, String> {

    private String errorMessage;

    public RestServiceTask() {

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String url = params[1];
        String method = params[2];
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 60000);
        HttpConnectionParams.setSoTimeout(httpParameters, 60000);
        HttpClient client = new DefaultHttpClient(httpParameters);

        HttpUriRequest request;
        try {

            if (method.equals("get")) {
                request = new HttpGet(url);
            } else {
                request = new HttpPost(url);

                if (params.length > 0 && params[0] != null) {
                    StringEntity entity = new StringEntity(params[0]);
                    ((HttpPost) request).setEntity(entity);
                    Crashlytics.log(Log.INFO, "Request", params[0]);
                }

                ((HttpPost) request).setHeader("Content-Type",
                        "application/json");
            }

            HttpResponse response = client.execute(request);
            HttpEntity entity = response.getEntity();

            String json = convertStreamToString(entity.getContent());
            Crashlytics.log(Log.INFO, "Response", json);
            return json;
        } catch (Exception e) {

        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //process your result 
    }

    public String convertStreamToString(InputStream is) throws IOException {
        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is,
                        "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }
}

使用它:

new RestServiceTask().execute("<json string>",url,method);//method can be get,post

答案 2 :(得分:0)

如果您对此链接有任何疑问,请尝试这个简单示例:

     HttpClient httpclient = new DefaultHttpClient();
     HttpPost httppost = new HttpPost("http://www.codeincloud.tk/First.php");
   try {
       HttpResponse response = httpclient.execute(httppost);
       final String str =  EntityUtils.toString(response.getEntity());
       TextView tv = (TextView) findViewById(R.id.textView1);
       tv.setText(str);
    } 
   catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
    }

http://codeoncloud.blogspot.in/2012/07/android-php-web-service-client.html,http://sampleprogramz.com/android/singlewebservicecall.php

答案 3 :(得分:0)

您应该更改问题的标题,POST中没有queryString这样的东西。查询字符串参数仅在GET中添加,在POST中,您将在请求正文中传递数据。

此外,您可以将this与AsyncTask结合使用来解决您的问题

编辑:另外,请查看here以了解有关GET和POST的更多信息

答案 4 :(得分:0)

试试这个:

HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
HttpPost httpPost = new HttpPost(your website);

List<NameValuePair> entityParams = new ArrayList<NameValuePair>();
entityParams.add(new BasicNameValuePair("action", "postcomment"));
entityParams.add(new BasicNameValuePair("app_id", com.appbuilder.sdk.android.Statics.appId));
entityParams.add(new BasicNameValuePair("message", message1));
entityParams.add(new BasicNameValuePair("message2", message2));

httpPost.setEntity(new UrlEncodedFormEntity(entityParams, "utf-8"));

String resp = httpClient.execute(httpPost, new BasicResponseHandler());