Retrofit을 사용하여 REST 웹 서비스를 사용하기위한 간단한 Android 클라이언트- '서버에 연결하지 못했습니다'오류가 발생하는 이유

위안

나는 PHP로 약간의 Restful 웹 서비스를 작성했으며 (질문의 끝에 제공된 코드) 내 로컬 XAMPP 서버에 있습니다. http://localhost/Test8/?name=JavaURL로 사용하여 브라우저에서 액세스하면 예상대로 다음 데이터가 표시됩니다.

{"status":200,"status_message":"Book found","data":999}

이는 웹 서비스가 올바르게 작동 함을 의미합니다.

그런 다음 Retrofit 라이브러리를 사용하여이 웹 서비스를 사용하기 위해이 튜토리얼에 따라 Android 앱을 작성했습니다 . 내 코드는 다음과 같이 제공됩니다.

문제는 내가 얻을 출력이 있다는 것이다 Failed to connect to localhost/###.#.#.#:##어디 ###.#.#.#:##내 IP 주소입니다.

여기에 이미지 설명 입력

MainActivity.java :

package tests.retrofitusageone;

import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.mainActivity_textView);

        String url = "http://localhost/Test8/index.php?name=Java";
        //String url ="https://graph.facebook.com/youtube?fields=id,name,likes&access_token=1541785476124013|sWrV2Qgw_knjFiQheJ_iT5uir84";

        RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(url).build();

        RestInterface restInterface = restAdapter.create(RestInterface.class);

        restInterface.get_price(new Callback<RestJsonPojo>() {

            @Override
            public void success(RestJsonPojo restJsonPojo, Response response) {
                textView.setText("Price of the book: " + restJsonPojo.getData());
            }

            @Override
            public void failure(RetrofitError retrofitError) {
                String retrofitErrorString = retrofitError.getMessage();
                textView.setText(retrofitErrorString);
            }

        });
    }
}

RestJsonPojo.java :

package tests.retrofitusageone;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("org.jsonschema2pojo")
public class RestJsonPojo {
    @SerializedName("status")
    @Expose
    private Integer status;
    @SerializedName("status_message")
    @Expose
    private String statusMessage;
    @SerializedName("data")
    @Expose
    private Integer data;

    /**
     * 
     * @return The status
     */
    public Integer getStatus() {
        return status;
    }

    /**
     * 
     * @param status
     *            The status
     */
    public void setStatus(Integer status) {
        this.status = status;
    }

    /**
     * 
     * @return The statusMessage
     */
    public String getStatusMessage() {
        return statusMessage;
    }

    /**
     * 
     * @param statusMessage
     *            The status_message
     */
    public void setStatusMessage(String statusMessage) {
        this.statusMessage = statusMessage;
    }

    /**
     * 
     * @return The data
     */
    public Integer getData() {
        return data;
    }

    /**
     * 
     * @param data
     *            The data
     */
    public void setData(Integer data) {
        this.data = data;
    }
}

RestInterface.java :

package tests.retrofitusageone;

import retrofit.Callback;
import retrofit.http.GET;

interface RestInterface {

    //@GET("/youtube?fields=id,name,likes&access_token=1541785476124013|sWrV2Qgw_knjFiQheJ_iT5uir84")
    @GET("/index.php?name=Java")
    void get_price(Callback<RestJsonPojo>callback);
}

명백한:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="tests.retrofitusageone"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="23" />

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

activity_main :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/mainActivity_textView" />"

</RelativeLayout>

localhost / Test8 / index.php :

<?php

//Process client's request (via URL)
header("Content-Type:application/json");

if (  !empty($_GET['name'])  ) {
    $name = $_GET['name'];
    $price = get_price($name);

    if (empty($price)) {
        //Book not found
        deliver_response(200, 'Book not found!', NULL);
    } else {
        //Send the response with book price
        deliver_response(200, 'Book found', $price);
    }

} else {
    //throw invalid request
    deliver_response(400, "Invalid Request", NULL);
}



 //API Functions
 function get_price($bookRequested) {
     $books = array(
        'Java' => 999,
        'C' => 348,
        'PHP' =>500
     );

     foreach ($books as $book=>$price) {
         if ($book == $bookRequested) {
             return $price;
         }
     }
 }


 function deliver_response($status, $status_message, $data) {
     header("HTTP/1.1 $status $status_message");

     $response['status'] = $status;
     $response['status_message'] = $status_message;
     $response['data'] = $data;

     $json_response = json_encode($response);

     echo $json_response;
 }

?>
베니 아민 프

당신의 안드로이드 장치에서 당신은 넣어서는 안되며 localhost/###.#.#.#:##, 대신 서버 주소와 포트 ###.#.#.#:##를 예를 들어 192.168.1.12:80. Android 앱에서 서버를 실행하지 않기 때문입니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관