AndroidからJSONをポストする

HttpPostクラスを使う.AndroidからXMLをPOSTすることはあまりない.通常はJSONを使う.

AndroidManifest.xmlandroid.permissions.INTERNETを設定する必要がある.

Androidエミュレータから外部APIに接続する場合,localhostを指定してはいけない.locaohostはエミュレータ自身.ホストマシンは10.0.2.2というアドレスが割り当てられる.

HttpPost httpPost = new HttpPost(url);
DefaultHttpClient client = new DefaultHttpClient();
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();

nameValuePair.add(new BasicNameValuePair("Json", jsonString));

try{
  httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair, "utf-8"));
  HttpResponse response = client.execute(httpPost);
  System.out.println(response.getStatusLine());
} catch (UnsupportedEncodingException e) {
  e.printStackTrace();
} catch (ClientProtocolException e) {
  e.printStackTrace();
} catch (IOException e) {
  e.printStackTrace();
} finally {

}

UIスレッド上でネットワークアクセスしようとするとNetworkOnMainThreadExceptionが発生する. 無名関数を使うのが手っ取り早いかな?

(new Thread(new Runnable() {
     @Override
     public void run(){
          //処理
     }
})).start();