まず、あなたはあなたのアプリケーションのための連絡先(Webサービス、RESTサービスまたは任意のニーズに合った)のポイントを開発しなければなりません。私の場合は、JSONレスポンスを生成するPHPスクリプトを使用しています。ここで
は、データベースおよび出力にJSON(
json_encode method)応答を接続する簡単なPHPスクリプトです:
<?php
$link = mysqli_connect("localhost", "dbuser", "dbpassword", "database");
$response = array();
$pass = mysqli_query("select * from table");
while($data = mysqli_fetch_object($pass))
{
array_push($response, array(
"my_field" => $data->my_field
));
}
echo json_encode($response);
mysqli_close($link);
>
スクリプトが出力されます。このようなJSONレスポンス:?
[{"my_field":1}]
アプリケーションがHTTP POSTまたはGET応答を使用してデータを要求すると、ライブラリを使用して答えを解析します。私はPHP側でJSONを使用しているので、現在私のプロジェクトにはGSONを使用しています。することができます、あなたのAndroidアプリに続いて
public class RestClient
{
private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private String url;
private int responseCode;
private String message;
private String response;
public enum RequestMethod
{
GET,
POST
}
public String getResponse() {
return response;
}
public String getErrorMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public RestClient(String url)
{
this.url = url;
params = new ArrayList<NameValuePair>();
headers = new ArrayList<NameValuePair>();
}
// -------------------------------------------------------------------------------
// Various methods.
// -------------------------------------------------------------------------------
/**
* Add a parameter to the request (pair, name/value).
* @param name Name of the parameter (ex: &name=)
* @param value Value of the parameter (ex: &name=value).
*/
public void AddParam(String name, String value)
{
params.add(new BasicNameValuePair(name, value));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Add a header to the request (if needed).
* @param name Name of the header. (ex: Content-Type)
* @param value Value of the header. (ex: Content-Type = text/html).
*/
public void AddHeader(String name, String value)
{
headers.add(new BasicNameValuePair(name, value));
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Fetch the HTTP content via POST or GET.
* @param method Method to be used.
* @throws Exception Exception to be catched in case of a network problem.
*/
public void Execute(RequestMethod method) throws Exception
{
switch(method) {
case GET:
{
//add parameters
String combinedParams = "";
if(!params.isEmpty()){
combinedParams += "?";
for(NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if(combinedParams.length() > 1)
{
combinedParams += "&" + paramString;
}
else
{
combinedParams += paramString;
}
}
}
HttpGet request = new HttpGet(url + combinedParams);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
executeRequest(request, url);
break;
}
case POST:
{
HttpPost request = new HttpPost(url);
//add headers
for(NameValuePair h : headers)
{
request.addHeader(h.getName(), h.getValue());
}
if(!params.isEmpty()){
request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
}
executeRequest(request, url);
break;
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Alternative method to execute the HTTP request.
* @param request The HTTP request object to be used.
* @param url HTTP url.
*/
private void executeRequest(HttpUriRequest request, String url)
{
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try {
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
response = convertStreamToString(instream);
// Closing the input stream will trigger connection release
instream.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/**
* Private method. Convert an HTTP stream to a string stream.
* @param is InputStream to be converted.
* @return String to be used.
*/
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
:
あなたは、私が(覚えていないこと)どこかにかかっRestClassを使用することができ、あなたのAndroidアプリケーションからJSONデータを要求するが、ここでコードがあります(あなたもPOSTを追加したり、クエリにパラメータを取得することができます)このようなRestClientクラスをインスタンス化:
RestClient c = new RestClient("http://www.myserver.com/json.php");
c.AddParam("my_field_value", 1);
try
{
c.Execute(RequestMethod.POST);
// Here you can parse the JSON with an instance of Gson class.
Gson jsonObject = new Gson();
String jsonOutput = jsonObject.toJson(c.getResponse());
// Do whatever you need with the data.
}
catch (Exception e)
{
e.printStackTrace();
}
出来上がりを!あなたのAndroidアプリケーションからPHPスクリプトで作成されたJSONデータを使用することができます。 AndroidManifest.xmlにandroid.permission.INTERNETを追加することを忘れないでください。そうしないと、アプリケーションはPHPスクリプトと通信できなくなります。
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
幸運。
閉どうして?少なくとも4人がこの質問を簡単に答えてくれました。彼らは非常にうまく答えてくれました。 – uTubeFan