HttpURLConnectionを使用してPOST送信する方法です。
テキストのみの送信です。
contentBuilderの形式は一定なので、送信したいデータをHashMapに入れておいてforで繰り返すと楽かもしれません。
HashMapに入れたデータを引数で渡す形にすると、汎用クラスとして使用できます。
また、さくらサーバーではこの方法でPOSTしてもPHP側でデータを取得できません。
非常に謎です。。。
さくらサーバーに置いたPHPなどにPOSTしたい場合は、Socketを利用するとうまくいきます。
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.Random; import android.os.Build; public class PostTask { private final static String TWO_HYPHEN = "--"; private final static String EOL = "\r\n"; private final static String BOURDARY = String.format("%x", new Random().hashCode()); private final static String CHARSET = "UTF-8"; public String post(String requestUrl) { String result = ""; // 送信するコンテンツを成形する StringBuilder contentsBuilder = new StringBuilder(); int iContentsLength = 0; contentsBuilder.append(String.format("%s%s%s", TWO_HYPHEN, BOURDARY, EOL)); contentsBuilder.append(String.format("Content-Disposition: form-data; name=\"keyName1\"%s", EOL)); contentsBuilder.append(EOL); contentsBuilder.append("value1"); contentsBuilder.append(EOL); contentsBuilder.append(String.format("%s%s%s", TWO_HYPHEN, BOURDARY, EOL)); contentsBuilder.append(String.format("Content-Disposition: form-data; name=\"keyName2\"%s", EOL)); contentsBuilder.append(EOL); contentsBuilder.append("value2"); contentsBuilder.append(EOL); contentsBuilder.append(String.format("%s%s%s", TWO_HYPHEN, BOURDARY, EOL)); contentsBuilder.append(String.format("Content-Disposition: form-data; name=\"keyName3\"%s", EOL)); contentsBuilder.append(EOL); contentsBuilder.append("value3"); contentsBuilder.append(EOL); contentsBuilder.append(String.format("%s%s%s%s", TWO_HYPHEN, BOURDARY, TWO_HYPHEN, EOL)); // コンテンツの長さを取得 try { // StringBuilderを文字列に変化してからバイト長を取得しないと // 実際送ったサイズと異なる場合があり、コンテンツを正しく送信できなくなる iContentsLength = contentsBuilder.toString().getBytes(CHARSET).length; } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } // サーバへ接続する HttpURLConnection connection = null; DataOutputStream os = null; BufferedReader br = null; try { URL url = new URL(requestUrl); connection = (HttpURLConnection)url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); // キャッシュを使用しない connection.setUseCaches(false); // HTTPストリーミングを有効にする connection.setChunkedStreamingMode(0); // リクエストヘッダを設定する // リクエストメソッドの設定 connection.setRequestMethod("POST"); // 持続接続を設定 connection.setRequestProperty("Connection", "Keep-Alive"); // ユーザエージェントの設定(必須ではない) connection.setRequestProperty("User-Agent", String.format("Mozilla/5.0 (Linux; U; Android %s;)", Build.VERSION.RELEASE)); // POSTデータの形式を設定 connection.setRequestProperty("Content-Type", String.format("text/plain; boundary=%s", BOURDARY)); // POSTデータの長さを設定 connection.setRequestProperty("Content-Length", String.valueOf(iContentsLength)); // データを送信する os = new DataOutputStream(connection.getOutputStream()); os.writeBytes(contentsBuilder.toString()); // レスポンスを受信する int iResponseCode = connection.getResponseCode(); // 接続が確立したとき if (iResponseCode == HttpURLConnection.HTTP_OK) { StringBuilder resultBuilder = new StringBuilder(); String line = ""; br = new BufferedReader(new InputStreamReader(connection.getInputStream())); // レスポンスの読み込み while ((line = br.readLine()) != null) { resultBuilder.append(String.format("%s%s", line, EOL)); } result = resultBuilder.toString(); } // 接続が確立できなかったとき else { result = String.valueOf(iResponseCode); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // 開いたら閉じる try { if (br != null) br.close(); if (os != null) { os.flush(); os.close(); } if (connection != null) connection.disconnect(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // 代入したレスポンスを返す return result; } }
Excellent article. I am dealing with some of these issues as well..
Greate pieces. Keep writing such kind of information on your page. Im really impressed by it
My brother suggested I may like this web site. He was once totally right. This submit truly made my day. You cann’t imagine just how much time I had spent for this information! Thanks!
Awesome! Its actually remarkable post, I have got much clear idea concerning from this piece of writing.