HTTP POST
でリクエストURL
を送信し、AndroidでBody
使用して応答を取得する方法は?HTTP POST
例えば
ありがとう。
Web ページを表示するために認証が必要かどうかによって異なります。
認証の必要の有無にかかわらず、Web ページにアクセスできるようにするには、マニフェストに次のアクセス許可を追加する必要があります。
<uses-permission android:name="android.permission.INTERNET"/>
アクセスを行うアクティビティまたはクラスでは、次のことができます。
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
public class YourClass
{
BufferedReader intro=null;
String url="Your Site URL?Your request body";
DefaultHttpClient cliente=new DefaultHttpClient();
HttpPost post=new HttpPost(url);
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("username","Your username"));
nvps.add(new BasicNameValuePair("password","your password"));
try
{
post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
HttpResponse response = cliente.execute(post);
if(response.getStatusLine().getStatusCode()==200)//this means that you got the page
{
HttpEntity entity=response.getEntity();
intro=new BufferedReader(new InputStreamReader(entity.getContent()));
intro.readLine();
intro.close();
}
}
catch (UnsupportedEncodingException ex)
{
}
catch(IOException e)
{
}
}
最後に、これを考慮してください:
-認証を行っている場合は、「ユーザー名」フィールドと「パスワード」フィールド (BasicNameValuePair 内) に、Web ページによっては別の名前が含まれている可能性があることを考慮してください。
- BufferedReader の intro.readLine を使用すると、ファイルを読んでいるかのように Web ページを読んでいるため、html コードを表示しないように解析する必要がある場合があります。