私はPHP、JavaScriptおよび他の多くのスクリプト言語の経験がありますが、JavaやAndroidの経験はあまりありません。
POSTデータをPHPスクリプトに送信して結果を表示する方法を探しています。
* Android 6.0以降で動作するAnswerを更新しました。 @ Rohit Suthar 、 @ Tamis Bolvari 、 @ sudhiskr にコメントをありがとう。 *
public class CallAPI extends AsyncTask<String, String, String> {
public CallAPI(){
//set context variables if required
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void doInBackground(String... params) {
String urlString = params[0]; // URL to call
String data = params[1]; //data to post
OutputStream out = null;
try {
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
参考文献:
古い答え
注:この解決方法は時代遅れです。それは5.1までのAndroidデバイスでのみ動作します。 Android 6.0以上には、この回答で使用されているApache httpクライアントは含まれていません。
Apache CommonsのHttp Clientがその方法です。それはすでにAndroidに含まれています。これを使用してHTTP Postを実行する方法の簡単な例を示します。
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "Hi"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
Android => 5
org.Apache.http クラスおよび AndroidHttpClient クラスは 非推奨 in Android 5.1 になりました。これらのクラスはメンテナンスされなくなったため、これらのAPIを使用しているアプリコードをできるだけ早く URLConnection クラスに移行する必要があります。
https://developer.Android.com/about/versions/Android-5.1.html#http
HttpUrlConnection を使って自分のコードを共有しようと思った
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response="";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
...
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
Post methodも使えます。
conn.setRequestMethod("POST");
更新21/02/2016
post request/ json の場合は、次の例を参照してください。
public class Empty extends
AsyncTask<Void, Void, Boolean> {
String urlString = "http://www.yoursite.com/";
private final String TAG = "post json example";
private Context context;
private int advertisementId;
public Empty(Context contex, int advertisementId) {
this.context = contex;
this.advertisementId = advertisementId;
}
@Override
protected void onPreExecute() {
Log.e(TAG, "1 - RequestVoteTask is about to start...");
}
@Override
protected Boolean doInBackground(Void... params) {
boolean status = false;
String response = "";
Log.e(TAG, "2 - pre Request to response...");
try {
response = performPostCall(urlString, new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
put("Accept", "application/json");
put("Content-Type", "application/json");
}
});
Log.e(TAG, "3 - give Response...");
Log.e(TAG, "4 " + response.toString());
} catch (Exception e) {
// displayLoding(false);
Log.e(TAG, "Error ...");
}
Log.e(TAG, "5 - after Response...");
if (!response.equalsIgnoreCase("")) {
try {
Log.e(TAG, "6 - response !empty...");
//
JSONObject jRoot = new JSONObject(response);
JSONObject d = jRoot.getJSONObject("d");
int ResultType = d.getInt("ResultType");
Log.e("ResultType", ResultType + "");
if (ResultType == 1) {
status = true;
}
} catch (JSONException e) {
// displayLoding(false);
// e.printStackTrace();
Log.e(TAG, "Error " + e.getMessage());
} finally {
}
} else {
Log.e(TAG, "6 - response is empty...");
status = false;
}
return status;
}
@Override
protected void onPostExecute(Boolean result) {
//
Log.e(TAG, "7 - onPostExecute ...");
if (result) {
Log.e(TAG, "8 - Update UI ...");
// setUpdateUI(adv);
} else {
Log.e(TAG, "8 - Finish ...");
// displayLoding(false);
// finish();
}
}
public String performPostCall(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(context.getResources().getInteger(
R.integer.maximum_timeout_to_server));
conn.setConnectTimeout(context.getResources().getInteger(
R.integer.maximum_timeout_to_server));
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json");
Log.e(TAG, "11 - url : " + requestURL);
/*
* JSON
*/
JSONObject root = new JSONObject();
//
String token = Static.getPrefsToken(context);
root.put("securityInfo", Static.getSecurityInfo(context));
root.put("advertisementId", advertisementId);
Log.e(TAG, "12 - root : " + root.toString());
String str = root.toString();
byte[] outputBytes = str.getBytes("UTF-8");
OutputStream os = conn.getOutputStream();
os.write(outputBytes);
int responseCode = conn.getResponseCode();
Log.e(TAG, "13 - responseCode : " + responseCode);
if (responseCode == HttpsURLConnection.HTTP_OK) {
Log.e(TAG, "14 - HTTP_OK");
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
Log.e(TAG, "14 - False - HTTP_OK");
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
}
2016年8月24日更新
次のようないくつかの最高のライブラリを使用してください。
なぜなら
低いAPIレベル(主にGingerbreadとFroyo)では、HttpUrlConnectionとHttpClientは完璧ではありません。
Honeycomb(API 11)の導入以降、メインスレッドとは異なる別のスレッドでネットワーク操作を実行することが必須になりました。
これにより、http postメソッドでデータを送信して結果を得ることができます
public class MyHttpPostProjectActivity extends Activity implements OnClickListener {
private EditText usernameEditText;
private EditText passwordEditText;
private Button sendPostReqButton;
private Button clearButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
usernameEditText = (EditText) findViewById(R.id.login_username_editText);
passwordEditText = (EditText) findViewById(R.id.login_password_editText);
sendPostReqButton = (Button) findViewById(R.id.login_sendPostReq_button);
sendPostReqButton.setOnClickListener(this);
clearButton = (Button) findViewById(R.id.login_clear_button);
clearButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if(v.getId() == R.id.login_clear_button){
usernameEditText.setText("");
passwordEditText.setText("");
passwordEditText.setCursorVisible(false);
passwordEditText.setFocusable(false);
usernameEditText.setCursorVisible(true);
passwordEditText.setFocusable(true);
}else if(v.getId() == R.id.login_sendPostReq_button){
String givenUsername = usernameEditText.getEditableText().toString();
String givenPassword = passwordEditText.getEditableText().toString();
System.out.println("Given username :" + givenUsername + " Given password :" + givenPassword);
sendPostRequest(givenUsername, givenPassword);
}
}
private void sendPostRequest(String givenUsername, String givenPassword) {
class SendPostReqAsyncTask extends AsyncTask<String, Void, String>{
@Override
protected String doInBackground(String... params) {
String paramUsername = params[0];
String paramPassword = params[1];
System.out.println("*** doInBackground ** paramUsername " + paramUsername + " paramPassword :" + paramPassword);
HttpClient httpClient = new DefaultHttpClient();
// In a POST request, we don't pass the values in the URL.
//Therefore we use only the web page URL as the parameter of the HttpPost argument
HttpPost httpPost = new HttpPost("http://www.nirmana.lk/hec/Android/postLogin.php");
// Because we are not passing values over the URL, we should have a mechanism to pass the values that can be
//uniquely separate by the other end.
//To achieve that we use BasicNameValuePair
//Things we need to pass with the POST request
BasicNameValuePair usernameBasicNameValuePair = new BasicNameValuePair("paramUsername", paramUsername);
BasicNameValuePair passwordBasicNameValuePAir = new BasicNameValuePair("paramPassword", paramPassword);
// We add the content that we want to pass with the POST request to as name-value pairs
//Now we put those sending details to an ArrayList with type safe of NameValuePair
List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
nameValuePairList.add(usernameBasicNameValuePair);
nameValuePairList.add(passwordBasicNameValuePAir);
try {
// UrlEncodedFormEntity is an entity composed of a list of url-encoded pairs.
//This is typically useful while sending an HTTP POST request.
UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(nameValuePairList);
// setEntity() hands the entity (here it is urlEncodedFormEntity) to the request.
httpPost.setEntity(urlEncodedFormEntity);
try {
// HttpResponse is an interface just like HttpPost.
//Therefore we can't initialize them
HttpResponse httpResponse = httpClient.execute(httpPost);
// According to the Java API, InputStream constructor do nothing.
//So we can't initialize InputStream although it is not an interface
InputStream inputStream = httpResponse.getEntity().getContent();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while((bufferedStrChunk = bufferedReader.readLine()) != null){
stringBuilder.append(bufferedStrChunk);
}
return stringBuilder.toString();
} catch (ClientProtocolException cpe) {
System.out.println("First Exception caz of HttpResponese :" + cpe);
cpe.printStackTrace();
} catch (IOException ioe) {
System.out.println("Second Exception caz of HttpResponse :" + ioe);
ioe.printStackTrace();
}
} catch (UnsupportedEncodingException uee) {
System.out.println("An Exception given because of UrlEncodedFormEntity argument :" + uee);
uee.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(result.equals("working")){
Toast.makeText(getApplicationContext(), "HTTP POST is working...", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(), "Invalid POST req...", Toast.LENGTH_LONG).show();
}
}
}
SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();
sendPostReqAsyncTask.execute(givenUsername, givenPassword);
}
}
これは、外部のApacheライブラリを使用せずにマルチパートデータをPOSTする方法の例です。
byte[] buffer = getBuffer();
if(buffer.length > 0) {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "RQdzAAihJq7Xp1kjraqf";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
// Send parameter #1
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"param1\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=US-ASCII" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: 8bit" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(myStringData + lineEnd);
// Send parameter #2
//dos.writeBytes(twoHyphens + boundary + lineEnd);
//dos.writeBytes("Content-Disposition: form-data; name=\"param2\"" + lineEnd + lineEnd);
//dos.writeBytes("foo2" + lineEnd);
// Send a binary file
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"param3\";filename=\"test_file.dat\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
dos.writeBytes(lineEnd);
dos.write(buffer);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
ByteArrayInputStream content = new ByteArrayInputStream(baos.toByteArray());
BasicHttpEntity entity = new BasicHttpEntity();
entity.setContent(content);
HttpPost httpPost = new HttpPost(myURL);
httpPost.addHeader("Connection", "Keep-Alive");
httpPost.addHeader("Content-Type", "multipart/form-data; boundary="+boundary);
//MultipartEntity entity = new MultipartEntity();
//entity.addPart("param3", new ByteArrayBody(buffer, "test_file.dat"));
//entity.addPart("param1", new StringBody(myStringData));
httpPost.setEntity(entity);
/*
String httpData = "";
ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
entity.writeTo(baos1);
httpData = baos1.toString("UTF-8");
*/
/*
Header[] hdrs = httpPost.getAllHeaders();
for(Header hdr: hdrs) {
httpData += hdr.getName() + " | " + hdr.getValue() + " |_| ";
}
*/
//Log.e(TAG, "httpPost data: " + httpData);
response = httpClient.execute(httpPost);
}
レスポンスを文字列に変換する方法を追加します。
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
これはconvertStramToString の例です。
これを使用して、HTTP POSTリクエストをURLに送信できます。あなたは簡単にリクエストを送ってレスポンスを得ることができます。私はいつもこれを使います。私は元気です。
///////////////////// Check SubScription ////////////////////
try {
AsyncHttpClient client = new AsyncHttpClient();
// Http Request Params Object
RequestParams params = new RequestParams();
String u = "B2mGaME";
String au = "gamewrapperB2M";
// String mob = "880xxxxxxxxxx";
params.put("usr", u.toString());
params.put("aut", au.toString());
params.put("uph", MobileNo.toString());
// params.put("uph", mob.toString());
client.post("http://196.6.13.01:88/ws/game_wrapper_reg_check.php", params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
playStatus = response;
//////Get your Response/////
Log.i(getClass().getSimpleName(), "Response SP Status. " + playStatus);
}
@Override
public void onFailure(Throwable throwable) {
super.onFailure(throwable);
}
});
} catch (Exception e) {
e.printStackTrace();
}
また、libs foldeにbellow Jarファイルを追加する必要があります。
Android-async-http-1.3.1.jar
最後にbuild.gradleを編集してください
dependencies {
compile files('libs/<Android-async-http-1.3.1.jar>')
}
最後にプロジェクトを再構築します。
Apache Commons HttpClientの使用を改善してください。これはすでにAndroidにも含まれています。一般的なAPI情報については、 Android開発者:Apache HTTPクライアントパッケージの概要 をご覧ください。
URLConnection
と setDoOutput
(true)
、 getOutputStream()
(データ送信用)、およびgetInputStream()
(受信用) Sunは 例を正確にこのに持っています。
私のために次に働きます:
private sendData() {
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("key1", value1);
jsonObject.accumulate("key2", value2);
boolean success = sendPost(SERVER_URL + "/v1/auth", jsonObject);
}
private boolean sendPost(String url, JSONObject parameters) {
boolean requestResult = false;
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
json = parameters.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null) {
result = convertInputStreamToString(inputStream);
requestResult = true;
} else {
result = "Did not work!";
requestResult = false;
}
System.out.println(result);
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
requestResult = false;
}
return requestResult;
}
私は この 便利な例を この ビデオチュートリアルで見つけました。
コネクタクラス
package com.tutorials.hp.mysqlinsert;
import Java.io.IOException;
import Java.net.HttpURLConnection;
import Java.net.MalformedURLException;
import Java.net.URL;
/**
* Created by Oclemmy on 3/31/2016 for ProgrammingWizards Channel.
*/
public class Connector {
/*
1.SHALL HELP US ESTABLISH A CONNECTION TO THE NETWORK
2. WE ARE MAKING A POST REQUEST
*/
public static HttpURLConnection connect(String urlAddress) {
try
{
URL url=new URL(urlAddress);
HttpURLConnection con= (HttpURLConnection) url.openConnection();
//SET PROPERTIES
con.setRequestMethod("POST");
con.setConnectTimeout(20000);
con.setReadTimeout(20000);
con.setDoInput(true);
con.setDoOutput(true);
//RETURN
return con;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
DataPackagerクラス:
package com.tutorials.hp.mysqlinsert;
import org.json.JSONException;
import org.json.JSONObject;
import Java.io.UnsupportedEncodingException;
import Java.net.URLEncoder;
import Java.util.Iterator;
/**
* Created by Oclemmy on 3/31/2016 for ProgrammingWizards Channel.
* 1.BASICALLY PACKS DATA WE WANNA SEND
*/
public class DataPackager {
String name,position,team;
/*
SECTION 1.RECEIVE ALL DATA WE WANNA SEND
*/
public DataPackager(String name, String position, String team) {
this.name = name;
this.position = position;
this.team = team;
}
/*
SECTION 2
1.PACK THEM INTO A JSON OBJECT
2. READ ALL THIS DATA AND ENCODE IT INTO A FROMAT THAT CAN BE SENT VIA NETWORK
*/
public String packData()
{
JSONObject jo=new JSONObject();
StringBuffer packedData=new StringBuffer();
try
{
jo.put("Name",name);
jo.put("Position",position);
jo.put("Team",team);
Boolean firstValue=true;
Iterator it=jo.keys();
do {
String key=it.next().toString();
String value=jo.get(key).toString();
if(firstValue)
{
firstValue=false;
}else
{
packedData.append("&");
}
packedData.append(URLEncoder.encode(key,"UTF-8"));
packedData.append("=");
packedData.append(URLEncoder.encode(value,"UTF-8"));
}while (it.hasNext());
return packedData.toString();
} catch (JSONException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
}
送信者クラス
package com.tutorials.hp.mysqlinsert;
import Android.app.ProgressDialog;
import Android.content.Context;
import Android.os.AsyncTask;
import Android.widget.EditText;
import Android.widget.Toast;
import Java.io.BufferedReader;
import Java.io.BufferedWriter;
import Java.io.IOException;
import Java.io.InputStreamReader;
import Java.io.OutputStream;
import Java.io.OutputStreamWriter;
import Java.net.HttpURLConnection;
/**
* Created by Oclemmy on 3/31/2016 for ProgrammingWizards Channel and Camposha.com.
* 1.SEND DATA FROM EDITTEXT OVER THE NETWORK
* 2.DO IT IN BACKGROUND THREAD
* 3.READ RESPONSE FROM A SERVER
*/
public class Sender extends AsyncTask<Void,Void,String> {
Context c;
String urlAddress;
EditText nameTxt,posTxt,teamTxt;
String name,pos,team;
ProgressDialog pd;
/*
1.OUR CONSTRUCTOR
2.RECEIVE CONTEXT,URL ADDRESS AND EDITTEXTS FROM OUR MAINACTIVITY
*/
public Sender(Context c, String urlAddress,EditText...editTexts) {
this.c = c;
this.urlAddress = urlAddress;
//INPUT EDITTEXTS
this.nameTxt=editTexts[0];
this.posTxt=editTexts[1];
this.teamTxt=editTexts[2];
//GET TEXTS FROM EDITEXTS
name=nameTxt.getText().toString();
pos=posTxt.getText().toString();
team=teamTxt.getText().toString();
}
/*
1.SHOW PROGRESS DIALOG WHILE DOWNLOADING DATA
*/
@Override
protected void onPreExecute() {
super.onPreExecute();
pd=new ProgressDialog(c);
pd.setTitle("Send");
pd.setMessage("Sending..Please wait");
pd.show();
}
/*
1.WHERE WE SEND DATA TO NETWORK
2.RETURNS FOR US A STRING
*/
@Override
protected String doInBackground(Void... params) {
return this.send();
}
/*
1. CALLED WHEN JOB IS OVER
2. WE DISMISS OUR PD
3.RECEIVE A STRING FROM DOINBACKGROUND
*/
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
pd.dismiss();
if(response != null)
{
//SUCCESS
Toast.makeText(c,response,Toast.LENGTH_LONG).show();
nameTxt.setText("");
posTxt.setText("");
teamTxt.setText("");
}else
{
//NO SUCCESS
Toast.makeText(c,"Unsuccessful "+response,Toast.LENGTH_LONG).show();
}
}
/*
SEND DATA OVER THE NETWORK
RECEIVE AND RETURN A RESPONSE
*/
private String send()
{
//CONNECT
HttpURLConnection con=Connector.connect(urlAddress);
if(con==null)
{
return null;
}
try
{
OutputStream os=con.getOutputStream();
//WRITE
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
bw.write(new DataPackager(name,pos,team).packData());
bw.flush();
//RELEASE RES
bw.close();
os.close();
//HAS IT BEEN SUCCESSFUL?
int responseCode=con.getResponseCode();
if(responseCode==con.HTTP_OK)
{
//GET EXACT RESPONSE
BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuffer response=new StringBuffer();
String line;
//READ LINE BY LINE
while ((line=br.readLine()) != null)
{
response.append(line);
}
//RELEASE RES
br.close();
return response.toString();
}else
{
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
主な活動:
package com.tutorials.hp.mysqlinsert;
import Android.os.Bundle;
import Android.support.v7.app.AppCompatActivity;
import Android.support.v7.widget.Toolbar;
import Android.view.View;
import Android.widget.Button;
import Android.widget.EditText;
/*
1.OUR LAUNCHER ACTIVITY
2.INITIALIZE SOME UI STUFF
3.WE START SENDER ON BUTTON CLICK
*/
public class MainActivity extends AppCompatActivity {
String urlAddress="http://10.0.2.2/Android/poster.php";
EditText nameTxt,posTxt,teamTxt;
Button saveBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//INITIALIZE UI FIELDS
nameTxt= (EditText) findViewById(R.id.nameEditTxt);
posTxt= (EditText) findViewById(R.id.posEditTxt);
teamTxt= (EditText) findViewById(R.id.teamEditTxt);
saveBtn= (Button) findViewById(R.id.saveBtn);
saveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//START ASYNC TASK
Sender s=new Sender(MainActivity.this,urlAddress,nameTxt,posTxt,teamTxt);
s.execute();
}
});
}
}
ContentMain.xml:
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:app="http://schemas.Android.com/apk/res-auto"
xmlns:tools="http://schemas.Android.com/tools"
Android:layout_width="match_parent"
Android:layout_height="match_parent"
Android:paddingBottom="@dimen/activity_vertical_margin"
Android:paddingLeft="@dimen/activity_horizontal_margin"
Android:paddingRight="@dimen/activity_horizontal_margin"
Android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context="com.tutorials.hp.mysqlinsert.MainActivity"
tools:showIn="@layout/activity_main">
<TextView
Android:layout_width="wrap_content"
Android:layout_height="wrap_content"
Android:text="Hello World!" />
<LinearLayout
Android:layout_width="fill_parent"
Android:layout_height="match_parent"
Android:layout_marginTop="?attr/actionBarSize"
Android:orientation="vertical"
Android:paddingLeft="15dp"
Android:paddingRight="15dp"
Android:paddingTop="50dp">
<Android.support.design.widget.TextInputLayout
Android:id="@+id/nameLayout"
Android:layout_width="match_parent"
Android:layout_height="wrap_content">
<EditText
Android:id="@+id/nameEditTxt"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:singleLine="true"
Android:hint= "Name" />
</Android.support.design.widget.TextInputLayout>
<Android.support.design.widget.TextInputLayout
Android:id="@+id/teamLayout"
Android:layout_width="match_parent"
Android:layout_height="wrap_content">
<EditText
Android:id="@+id/teamEditTxt"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:hint="Description" />
</Android.support.design.widget.TextInputLayout>
<Android.support.design.widget.TextInputLayout
Android:id="@+id/posLayout"
Android:layout_width="match_parent"
Android:layout_height="wrap_content">
<EditText
Android:id="@+id/posEditTxt"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:hint="Position" />
<!--Android:inputType="textPassword"-->
</Android.support.design.widget.TextInputLayout>
<Button Android:id="@+id/saveBtn"
Android:layout_width="fill_parent"
Android:layout_height="wrap_content"
Android:text="Save"
Android:clickable="true"
Android:background="@color/colorAccent"
Android:layout_marginTop="40dp"
Android:textColor="@Android:color/white"/>
</LinearLayout>
</RelativeLayout>
URLにデータを追加したいだけの場合は、HttpClientが廃止予定になっているため、HttpUrlConnectionを使用して行うことができます。もっと良い方法は、次のようなライブラリを使うことです。
バレーボールの改装
AsyncTaskクラスを介して実行されるこのコードを使用して、phpスクリプトにデータを投稿し、結果を取得して表示することができます。
private class LongOperation extends AsyncTask<String, Void, Void> {
// Required initialization
private String Content;
private String Error = null;
private ProgressDialog Dialog = new ProgressDialog(Login.this);
String data ="";
int sizeData = 0;
protected void onPreExecute() {
// NOTE: You can call UI Element here.
//Start Progress Dialog (Message)
Dialog.setMessage("Please wait..");
Dialog.show();
Dialog.setCancelable(false);
Dialog.setCanceledOnTouchOutside(false);
try{
// Set Request parameter
data +="&" + URLEncoder.encode("username", "UTF-8") + "="+edittext.getText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Call after onPreExecute method
protected Void doInBackground(String... urls) {
/************ Make Post Call To Web Server ***********/
BufferedReader reader=null;
// Send data
try
{
// Defined URL where to send data
URL url = new URL(urls[0]);
// Send POST data request
URLConnection conn = url.openConnection();
conn.setConnectTimeout(5000);//define connection timeout
conn.setReadTimeout(5000);//define read timeout
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
// Append server response in string
sb.append(line + " ");
}
// Append Server Response To Content String
Content = sb.toString();
}
catch(Exception ex)
{
Error = ex.getMessage();
}
finally
{
try
{
reader.close();
}
catch(Exception ex) {}
}
return null;
}
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
// Close progress dialog
Dialog.dismiss();
if (Error != null) {
Toast.makeText(getApplicationContext(),"Error encountered",Toast.LENGTH_LONG).show();
}
else {
try {
JSONObject jsonRootObject = new JSONObject(Content);
JSONObject json2 =jsonRootObject.getJSONObject("jsonkey");//pass jsonkey here
String id =json2.optString("id").toString();//parse json to string through parameters
//the result is stored in string id. you can display it now
} catch (JSONException e) {e.printStackTrace();}
}
}
}
しかし、AsynctaskクラスとHttpurlConnectionはライブラリに比べて遅いので、volleyやretrofitなどのライブラリを使用するほうがはるかに良い選択肢です。また、ライブラリはすべてを取得し、同様に速くなります。
Squareのオープンソース okHttp
ライブラリを使用してください。 okHttp
はAndroid 2.3以降で動作し、GitHubで Apache 2.0ライセンスを持っています 。
POSTデータの送信は、AsyncTaskに以下を追加するのと同じくらい簡単です。
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("email", emailString) // A sample POST field
.add("comment", commentString) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("https://yourdomain.org/callback.php") // The URL to send the data to
.post(formBody)
.build();
okHttp
もmavenに名前空間を持っているので、あなたのAndroid Studioプロジェクトに追加するのは簡単です。アプリのbuild.gradleにcompile 'com.squareup.okhttp3:okhttp:3.11.0'
を追加するだけです。
コード全体
アクティビティに以下を追加してください。
public class CallAPI extends AsyncTask<String, String, String> {
String emailString;
String commentString;
public CallAPI(String email, String commnt){
emailString = email;
commentString = commnt;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new FormBody.Builder()
.add("email", emailString) // A sample POST field
.add("comment", commentString) // Another sample POST field
.build();
Request request = new Request.Builder()
.url("https://yourdomain.org/callback.php") // The URL to send the data to
.post(formBody)
.build();
return "";
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
}
そしてそれを使ってそれを呼ぶ:
new CallAPI(emailString, commentString).execute();
WebServerクラスを使用してHttpRequestをPOSTし、そのリスナーインタフェースで応答を追跡できます。
WebServer server=new WebServer(getApplicationContext());
server.setOnServerStatusListner(new WebServer.OnServerStatusListner() {
@Override
public void onServerResponded(String responce) {
}
@Override
public void onServerRevoked() {
}
});
データをバインドするためのDataRackを作成しましょう
List<DataRack> racks=new ArrayList<DataRack>();
racks.add(new DataRack("name","Simon"));
racks.add(new DataRack("age","40"));
racks.add(new DataRack("location","Canada"));
そのラックにPOSTリクエストを送信するだけです。
server.connectWithPOST(MainActivity.this,"http://sangeethnandakumar.esy.es/PROJECTS/PUBLIC_SERVICE/posttest.php",racks);
これには私のライブラリを含める必要があります。ドキュメンテーション はこちら
HTTPリクエストとしてデータを送信する方法
public static InputStream callPostService(String Url,
List<NameValuePair> data) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Url);
try {
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
return entity.getContent();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Androidの新しいバージョンでは、すべてのWeb I/O要求を新しいスレッドに入れる必要があります。 AsyncTaskは小さなリクエストに最適です。